I have this array
[InstrumentCategory] => Array
(
[0] => Array
(
[id] => 4
[title] => Training
[InstrumentsCategory] => Array
(
[id] => 56
[instrument_id] => 28
[category_id] => 4
)
)
[1] => Array
(
[id] => 8
[title] => Working time flexibility
[InstrumentsCategory] => Array
(
[id] => 57
[instrument_id] => 28
[category_id] => 8
)
)
[2] => Array
(
[id] => 16
[title] => Income support for workers
[InstrumentsCategory] => Array
(
[id] => 55
[instrument_id] => 28
[category_id] => 16
)
)
开发者_JAVA百科 )
Is there any other way to extract id=>value pairs (note that id
in this case is a key in the sub-arrays) than a for
loop?
Thanks in advance
If you use PHP 5.3, you can use the following code (array_reduce):
$r = array_reduce($input_array,
function ($res, $cur) {
return $res + array($cur['id'] => $cur);
}, array());
Afterwards, $r
contains id => value pairs.
Edit: With a PHP version < 5.3, you can do the following:
function array_reduce_cb_id ($res, $cur) {
return $res + array($cur['id'] => $cur);
}
$r = array_reduce($input_array, 'array_reduce_cb_id', array());
精彩评论