I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
CodePudding user response:
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
CodePudding user response:
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result
will be the output array you wanted.
Using $x[0]
, you refer the first element of your input array (and hence, $x[1]
the second one, ...). Adding ['referrer_id']
will access its referrer_id
key. The surrounding array(...)
puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
CodePudding user response:
You may use array_column
to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map
and array_values
together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values
, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here