I have a multi dimensional array which stores my order details looks similar to the following
$Orders=Array
(
[0] => Array
(
[id] => 10
[name] => "Hello world"
[product_id] => 1234
)
[1] => Array
(
[id] => 40
[name] => "Test World"
[product_id] => 6066
)
[2] => Array
(
[id] => 70
[name] => "Sample World"
[product_id] => 1234
)
)
Now I want to get all the product_id
to one array like below array
array:8 [▼
0 => "1234"
1 => "6066"
2 => "1234"
]
I tried using phps's array_column
function
$newArr_pids = array_column($result_3['orders'], "product_id");
This gives me an error but when I change this as below it works,
$newArr_pids = array_column(array_column($result_3['orders']),'0'),'product_id');
Now as in my above example since I have 3 (this can be less than 3 or more than 3) indexes, and they are dynamic, how can I correct my function to create the $newArr_pids
array correctly
CodePudding user response:
$arr = array();
foreach($Orders as $key => $value) {
$arr[] = $value['product_id'];
}
The $arr
will get the values of product id
CodePudding user response:
Using array_column
<?php
$Orders = [
[
"id"=>10,
"name"=>"Hello world",
"product_id"=>1234
],
[
"id"=>40,
"name"=>"Test world",
"product_id"=>6066
],
[
"id"=>70,
"name"=>"Sample world",
"product_id"=>1234
],
];
print_r(array_column($Orders, "product_id"));
?>
Will return:
Array
(
[0] => 1234
[1] => 6066
[2] => 1234
)