Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Array mapping or filtering

Sorry for the vague title, I had trouble summarizing this question in one sentence (I'm open to suggestions or edits).

I have a 2 dimensional associative array with an array of 2 numbers for each key.

Like this:

Array
   (
   [one] => Array
      (
      [0] => 1
      [1] => 2
   )
   [two] => Array
      (
      [0] => 1
      [1] => 2
   )
   [three] => Array
      (
      [0] => 1
      [1] => 2
   )
)

I'm wondering if there is a way to use array_map() or array_filter() to return an array that has each key and the first number in each of the value arrays, like this:

Array
   (
   [one] => 1
   [two] => 1
   [three] => 1
)

I do not wish to create a new array by using a loop or anything like that, I'd like to do the conversion on the fly as an argument to a function, if you know what I mean.

I could write my own function to achieve this but I'm interested in knowing if it can be done with array_map() or array_filter().

I tried using various combinations of array_merge(), array_keys() and array_values() with no success.

I thank you in advance for any help you may provide.

like image 972
vulpinus Avatar asked Dec 18 '22 15:12

vulpinus


1 Answers

I think it would be better to use loop instead in this condition. However this one should work with your case.

<?php

$arr = array(
   "one" => array(1, 2),
   "two" => array(1, 2),
   "three" => array(1, 2)
);
$res = array();

array_walk($arr, function ($v, $k) use (&$res) {
    $res[$k] = $v[0];
});

print_r($res);
like image 65
Ammar Faizi Avatar answered Jan 03 '23 03:01

Ammar Faizi