How to parse a string array for a multidimensional array?

Asked

Viewed 89 times

7

I have the following array:

Array
(
    [0] => MemTotal:        4060964 kB
    [1] => MemFree:         3630320 kB
    [2] => MemAvailable:    3789472 kB
    [3] => Buffers:           93040 kB
    [4] => SwapCached:            0
    [6] => Active:           306312 kB
)

I need to rewrite this array so it looks like this:

Array
(
    [MemTotal]     => 4060964 kB
    [MemFree]      => 3630320 kB
    [MemAvailable] => 3789472 kB
    [Buffers]      =>   93040 kB
    [SwapCached]   =>       0
)

The rules would be:

  1. The index is everything that comes before two-points (:)
  2. The content is preceded by two-points and a sequence of one or more space characters

How to do this parse?

3 answers

6

Utilize explode() to separate the key ($str[0]) and the value ($str[1]) of each item in the array, after just matching the pair and assigning this element in the new array.

$arr = ['MemTotal:        4060964 kB',
        'MemFree:         3630320 kB',
        'MemAvailable:    3789472 kB',
        'Buffers:           93040 kB',
        'SwapCached:            0',
        'Active:           306312 kB'];

$novo = array();
foreach($arr as $item){
    $str = explode(':', $item);
    $novo[$str[0]] = trim($str[1]); 
}

5

In this example, I kept the same object.

Original indexes are removed as they are "converted"

$arr = array(
    'a:     1',
    'b: 4',
    'c:   2',
);

print_r($arr);

foreach ($arr as $k => $v) {
    $a = explode(':', $v);
    $arr[$a[0]] = trim($a[1]);
    unset($arr[$k]);
}

print_r($arr);

3

Utilize explode within an interaction (for) sweeping each line and transformed into another array:

$dados = array
(
    0 => 'MemTotal:        4060964 kB',
    1 => 'MemFree:         3630320 kB',
    2 => 'MemAvailable:    3789472 kB',
    3 => 'Buffers:           93040 kB',
    4 => 'SwapCached:            0',
    6 => 'Active:           306312 kB'
);


$dadosNew = array();
foreach($dados as $key => $value)
{
    $valueNew = explode(":", $value);
    $dadosNew[$valueNew[0]] = trim($valueNew[1]);
}

var_dump($dadosNew);

Example

  • 2

    Was the only one who picked up on the example given +1.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.