How to extract perticular array value from multidimentional array

馋奶兔 提交于 2021-01-29 05:02:36

问题


How can I get the list of all ids from the array given below,

$filteredZips=[{
    "id": 21,
    "distance": "0"
},
{
    "id": 20,
    "distance": "3.9399923305414037"
},
{
    "id": 29,
    "distance": "8.33045537474091"
}] 

Expected result will be :

$id = array('21','20','29');

回答1:


There is a function called array_column that will grab one column in an array.
First the string needs to be converted to array with Json_decode and second parameter to true.

Then array_column returns your expected output.

No looping is needed.

$filteredZips='[{
"id": 21,
"distance": "0"},{
"id": 20,
"distance": "3.9399923305414037"},{
"id": 29,
"distance": "8.33045537474091"}]';

$filteredZipsarr = json_decode($filteredZips,true);

$id = array_column($filteredZipsarr, "id");
Var_dump($id);

https://3v4l.org/hFOKR

If you don't need the $filteredZipsarr you can make it a one liner:

$id = array_column(json_decode($filteredZips,true), "id");



回答2:


Use array_map function:

$id = array_map(function($value){
   return $value['id'];
}, $filteredZips);

Documentation: http://php.net/manual/en/function.array-map.php




回答3:


First you need to decode JSON string to access it as Array of Objects :

$filteredZips = json_decode($filteredZips);

$results = array();
foreach ($filteredZips as $zip) {
    $results[] = $zip->id;
}

print_r($results);

Check here : https://3v4l.org/kfkhV




回答4:


Use array_column after transform your JSON with json_decode

$ids = array_column(json_decode($filteredZips, true), 'id');

Array
(
    [0] => 21
    [1] => 20
    [2] => 29
)



回答5:


Solution:

$answer = [];
foreach($filteredZips as $array){
    if(isset($array['id'])){
         $answer[]=$array['id'];
    }
}
var_dump($answer);



回答6:


Try this:

$ids = array();
foreach ($filteredZips as $zip) {
    $ids[] = $zip["id"];
 }
var_dump($ids);

Dont forget to use json_decode function to get a proper php array.



来源:https://stackoverflow.com/questions/48442659/how-to-extract-perticular-array-value-from-multidimentional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!