0

I have an array of arrays, something like this:

Array
(
[0] => Array
    (
        [0] => DC1F180E-FE57-622C-28AE-8194843B4D84
        [1] => First Choice
        [2] => 1
    )

[1] => Array
    (
        [0] => EB877F3C-7A3B-98A7-9240-580FB797030A
        [1] => Second Choice
        [2] => 0
    )

[2] => Array
    (
        [0] => D3C0EA56-73D2-C7E3-8236-EEA2400DFA9C
        [1] => Third Choice
        [2] => 0
    )

)

How do I can rename all the keys in "nested" arrays to get something like this in all "nested" arrays:

...
[1] => Array
    (
        [id] => EB877F3C-7A3B-98A7-9240-580FB797030A
        [name] => Second Choice
        [status] => 0
    )
...
Red October
  • 597
  • 2
  • 9
  • 29
  • It's unclear what you're asking. Are you trying to replace all the sub-arrays with this specific sub-array? – Amal Murali May 17 '14 at 10:41
  • @AmalMurali was the question edited in the grace period? Seems pretty clear (though it's definitely a duplicate). – AD7six May 17 '14 at 10:43

2 Answers2

1

This way you can change keys in your array:

for ($i=0, $c = count($array); $i<$c; ++$i) {
   $array[$i]['id'] = $array[$i][0];
   $array[$i]['name'] = $array[$i][1];
   $array[$i]['status'] = $array[$i][2];
   unset($array[$i][0];
   unset($array[$i][1];
   unset($array[$i][2];
}

You have to use syntax $array[$key1][$key2] to use multidimensional array.

Marcin Nabiałek
  • 104,635
  • 41
  • 242
  • 277
1

You could use array_walk and array_combine like this:

$a = array(array('foo','bar'),array('foo','bar'));
print_r($a);
$keys = array('first','second');
$new_array = array();
array_walk($a,function($x) use (&$new_array,$keys) { 
    $new_array[] = array_combine($keys,$x); 
});
print_r($new_array);

array_walk goes through each element of your array, applying a callback function. array_combine combines an array of keys with an array of values to produce a new array.

output:

Array ( [0] => Array ( [0] => foo [1] => bar ) 
        [1] => Array ( [0] => foo [1] => bar ) ) 

Array ( [0] => Array ( [first] => foo [second] => bar ) 
        [1] => Array ( [first] => foo [second] => bar ) )
Tom Fenech
  • 69,051
  • 12
  • 96
  • 131