2

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. :)

3 Answers 3

4

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

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

Comments

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

3 Comments

Although this solution works as expected, I personally think that array_reduce() is not the correct function for this use case as it's not a reduce-operation but rather a map-operation (in the context of map&reduce).
@Stefan Gehrig: in context of map-reduce - reduce part can reduce the mapped data in any way. It can even actually not reduce it at all.
OK, it just feels not really as if it's the correct function. But as it works, it shouldn't matter.
1

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

1 Comment

Note that the first example modifies the array by reference. Make a copy first if you need the original intact.

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.