murvinlai
murvinlai

Reputation: 50375

How to reduce an array's inner array value in PHP?

if I have the array like that:

array(
   array('id'=>123,'name'=>"Ele1"),
   array('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. :)

Upvotes: 2

Views: 2205

Answers (3)

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

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 ;-))

Upvotes: 4

Hamish
Hamish

Reputation: 23316

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']);

Upvotes: 1

zerkms
zerkms

Reputation: 254944

$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'));

Upvotes: 1

Related Questions