1

I wish to add string keys to my inner PHP arrays. So, I want to convert this:

array (size=2)
0 => array (size=3)
  0 => string 'X705' (length=4)
  1 => string 'X723' (length=4)
  2 => string 'Sue' (length=0)
1 => array (size=3)
  0 => string 'X714' (length=4)
  1 => string 'X721' (length=4)
  2 => string 'John' (length=0)

to this:

array (size=2)
0 => 
array (size=3)
  'code1' => string 'X705' (length=4)
  'code2' => string 'X723' (length=4)
  'name' => string 'Sue' (length=0)
1 => 
array (size=3)
  'code1' => string 'X714' (length=4)
  'code2' => string 'X721' (length=4)
  'name' => string 'John' (length=0)

I think I need to use array_walk but cannot fathom it out. Any help appreciated.

3
  • Do you need to modify the original array, or create a new array with the string keys? Commented Apr 23, 2015 at 15:54
  • Have you tried anything so far ? Commented Apr 23, 2015 at 15:54
  • You need an example of what you have tried. Commented Apr 23, 2015 at 16:15

3 Answers 3

4

You can use array_map for that purpose:

$newarray = array_map(function($x) {
    return array("code1" => $x[0], "code2" => $x[1], "name" => $x[2]);
}, $array); 

where $array is your input array.

Sign up to request clarification or add additional context in comments.

1 Comment

Just what I needed. Simple and elegant. Thank you.
0

Start with this:

foreach ($array as $key=>$item) {
  $item['code1']=$item[0];
  unset($item[0]);
  $item['code2']=$item[1];
  unset($item[1]);
  $item['name']=$item[2];
  unset($item[2]);
  $array[$key]=$item;
}

Comments

0

I would use array_map() but here's an alternate:

foreach($array as &$v) {
    $v = array_combine(array('code1','code2','name'), $v);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.