How to reduce an array's inner array value in PHP?
if I have the array like that:
array(
array('id'=>123,'name'=>"Ele1"),
arr开发者_如何学Pythonay('id'=>12233,'name'=>"Ele2"),
array('id'=>1003,'name'=>"Ele4"),
array('id'=>1233,'name'=>"Ele5")
)
That's the data I get and I want to effeciently remove 2nd value of every inner array. (e.g. "Ele1", "Ele2". .... )
here is what I do:
$numEle = count($arrayA);
$_arrayB = array();
for ($i=0; $i<$numEle ; $i++)
{
array_push($_arrayB , $arrayA[$i]['id']);
}
Instead of have a for loop to read and assign the value to a new array. What is the best way to do it? any php build-in function I should use?
like array_map?
I currently do that:
Thanks all for the answer. They all work. :)
When you're using PHP 5.3 the solution can be quite elegant:
$b = array_map(function($item) { return $item['id']; }, $arrayA);
On PHP < 5.3 you would have to create a callback function
function mapCallback($item) {
return $item['id'];
}
$b = array_map('mapCallback', $arrayA);
or use create_function()
to create a dynamic callback function (I won't show this, because it actually hurts my eyes ;-))
$s = array(
array('id'=>123,'name'=>"Ele1"),
array('id'=>12233,'name'=>"Ele2"),
array('id'=>1003,'name'=>"Ele4"),
array('id'=>1233,'name'=>"Ele5")
);
function reduce($a, $b)
{
$a[] = $b['id'];
return $a;
}
var_dump(array_reduce($s, 'reduce'));
Lots of ways:
Using array_walk:
array_walk($a, function(&$b) { unset($b['name']); });
Using array_map:
$b = array_map(function($el) { return array('id' => $el['id']); }, $a);
Simplifying your own example:
foreach($a as $key => $el)
$b[] = array('id' => $el['id']);
精彩评论