如何从多维数组中提取垂直数组值 [英] How to extract perticular array value from multidimentional array

查看:46
本文介绍了如何从多维数组中提取垂直数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从下面给出的数组中获取所有 id 的列表,

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"
}] 

预期结果是:

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

推荐答案

有一个名为 array_column 的函数可以抓取数组中的一列.
首先需要将字符串转换为带有 Json_decode 和第二个参数为 true 的数组.

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.

然后 array_column 返回您的预期输出.

Then array_column returns your expected output.

不需要循环.

$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

如果您不需要 $filteredZipsarr,您可以将其设为单行:

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

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

这篇关于如何从多维数组中提取垂直数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆