Search code examples
phparraysdynamic-arrays

Recreate Multidimensional Array in PHP


This is pretty basic, but my question is:

Given an array:

$a = array(
0 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_1', 'type'=>'day','value'=>10)),
1 => array('Rate'=> array('type_id'=>1, 'name' => 'Rate_2', 'type'=>'night','value'=>8)),
2 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_3', 'type'=>'day','value'=>7)),
3 => array('Rate'=> array('type_id'=>2, 'name' => 'Rate_4', 'type'=>'nigh','value'=>16)),
4 => array('Rate'=> array('type_id'=>3, 'name' => 'Rate_5', 'type'=>'day','value'=>10))
);

What is the most efficient way to change it so we have something like:

$new_array = array(
   [type_id] => array(
      [type] => array(
          [value]
          )
       )
    )
);

In other words, I would like to strip some data (the name, which I don't need) and reorganise the dimensions of the array. In the end I would have an array which I would be able to access the values by $new_array['type_id']['type']['value'].


Solution

  • Not entirely sure if this is exactly what you want, but with this you can access the values by saying

    echo $new[TYPE_ID][DAY_OR_NIGHT];

    $new = array();
    
    foreach($a AS $b){
        $c = $b['Rate'];
        $new[$c['type_id']][$c['type']] = $c['value'];
    }
    

    Using print_r on $new would give you:

    Array
    (
        [1] => Array
            (
                [day] => 10
                [night] => 8
            )
    
        [2] => Array
            (
                [day] => 7
                [night] => 16
            )
    
        [3] => Array
            (
                [day] => 10
            )
    
    )