How to parse a string array into a multidimensional array?

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:

  • The index is everything that comes before a colon (:)
  • Content is preceded by a colon and a sequence of one or more spaces characters
  • How to do this parse?

        
    asked by anonymous 24.11.2016 / 15:38

    3 answers

    6

    Use explode() to separate the key ( $str[0] ) and the value ( $str[1] ) of each item in the array, after combining the pair and assigning that element to 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]); 
    }
    
        
    24.11.2016 / 15:47
    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);
    
        
    24.11.2016 / 15:47
    3

    Use explode within an interaction ( for ) by sweeping each line and transforming it 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

        
    24.11.2016 / 15:47