What is the easiest way to change this array to a 1D array

What is the easiest way to change this array to a 1D array, I can do it using for loop or foreach, but I'm curious to check if there is an easier way. THANK

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
        )

    [2] => Array
        (
            [id] => 3
        )
)
+3
source share
3 answers
$output_ar = array_map('array_shift', $input_ar);

The function array_shift()captures the first key / value pair from the array and returns the value, so applying it to each of the arrays in your top-level array and combining the results will result in a 1-d list of identifiers.

, id , , , , , array_map.

+2

, , , .

function reducer($e, $i, $p){
    $e = $e[$p];
}

array_walk($array, 'reducer', "id");

, "id" ( ), .

+2

This will extract all the values ​​and put them in a new array.

// Initializing the Array
$arr0 ['id'] = 1;
$arr1 ['id'] = 2;
$arr2 ['id'] = 3;

$arr[0] = $arr0;
$arr[1] = $arr1;
$arr[2] = $arr2;


// Processing
$resultarray = array();
for ($i = 0; $i < count($arr); $i++){
  $resultarray = array_merge(array_values($arr[$i]),$resultarray);
}

// Test Output
print_r ($resultarray);
0
source

Source: https://habr.com/ru/post/1755258/


All Articles