Sample Code
<?php
$items = array(
array(
'forename' => 'Foo',
'surname' => 'Bar'
),
array(
'forename' => 'Bar',
'surname' => 'Foo'
)
);
$arr = array();
$i = 0;
foreach($items as $item){
$arr[$i]['name'] = $item['forename'];
$arr[$i]['surname'] = $item['surname'];
$i++;
}
echo "<pre>".print_r($arr, true)."</pre>";
?>
Result
Array
(
[0] => Array
(
[name] => Foo
[surname] => Bar
)
[1] => Array
(
[name] => Bar
[surname] => Foo
)
)
The result is perfectly acceptable and the code is readable.
My question is: is there a better / more efficient / prettier way to do this?
There isn’t a massive amount you could do to that code, you could get rid of the need to have an incremental variable (
$i) by usingforeach($items as $key => $value)and using$keyinstead of$i.