Reputation: 569
I have a two-dimensional array that looks something like this:
Array
(
[0] => Array
(
[0] => 1
[1] => John
[2] => Smith
[3] => 7
)
[1] => Array
(
[0] => 2
[1] => Robert
[2] => Williams
[3] => 4
)
)
I need to combine the row number from the top level (here: 0
and 1
) with the value in row 3 of the subordinate array of that row (here: 7
and 4
) into a new associative array, so that the new array looks like this:
Array
(
[0] => 7
[1] => 4
)
Is this possible without looping through each row?
$new = array();
foreach($old as $key => $value){
$new[$key] = $value[3];
}
I come from R, where we're taught to use functions (such as z <- sapply(x, quantile)
) or vectorized alternatives (such as z <- x - y
) instead of loops, but I'm not familiar with PHP so that may not be a concern here.
Upvotes: 0
Views: 36
Reputation: 16794
Whatever solution you choose, there will always be loops involved. That's how computers work.
However, in your case there's a handy PHP function that might speed things up a bit: array_column(). In your case this would already do the job:
$new = array_column($old, 3);
The looping here is done, implicitly, inside the function, which is probably slightly faster than doing it explicitly with a foreach
loop.
You might have noticed I ignored the array keys. That's because they are the normal numerical keys you would get anyway. However, in case that your question doesn't reflect the real data you have, and it often does on Stack Overflow, there is a way to keep the keys:
$keys = array_keys($old);
$values = array_column($old, 3);
$new = array_combine($keys, $values);
I cannot know if this will be faster than your loop, for the real data you have. You simply will have to test it.
You can, of course, write this in one line:
$new = array_combine(array_keys($old), array_column($old, 3));
Which is still readable and comprehensible. There's no real advantage to using just one line, so the 3 line version has my preference.
There are many other solutions, using array functions, but most of them won't be so easy to understand as this one.
Upvotes: 2