Php 如何获取某个数组参数的值并将其放入另一个数组中?
我有以下编码的JSON数组Php 如何获取某个数组参数的值并将其放入另一个数组中?,php,json,Php,Json,我有以下编码的JSON数组 { "canonList": [{ "deviceId": "Device123", "deviceModel": "Model123", "mapList": [{ "alarmStatus": true, "disabledEndDate": "2020-01-28T15:06:19", "lastUpdateDate": "2020-01-02T15:06:19", "rul
{
"canonList": [{
"deviceId": "Device123",
"deviceModel": "Model123",
"mapList": [{
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description"
}, {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 3"
}, {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 2"
}]
}, {
"deviceId": "Device1234",
"deviceModel": "Model1234",
"mapList": {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 5"
}
}],
"resultCode": 0,
"transactionId": "retrieve_1580400944"
}
我试图创建一个包含ruleDesc
的所有值的数组,但我只得到一个空值。该值的索引是动态的。有一件事是肯定的,我需要ruleDesc
中的值
我用过
$arrayName['canonList']['mapList']['ruleDesc']
但它只获取第一个数组的值
有什么想法吗 正如我看到的,JSON对象中有两个内部数组。第一个是
canonList
,第二个是mapList
,因此您必须迭代这两个元素,并将所需的值添加到结果数组中,如下所示:
$ruleDescs = [];
foreach ($arrayName['cannonList'] as $cannon) {
foreach ($cannon['mapList'] as $map) {
$ruleDescs[] = $map['ruleDesc'];
}
}
print_r($ruleDesc);
您需要首先提取所有
mapList
条目,这可以通过array\u column
完成。然后,您需要检查maplist
值是否具有ruleDesc
键,在这种情况下,您可以将该键添加到输出中;否则,将mapList
中的所有ruleDesc
合并到输出中:
$ruleDesc = array();
foreach (array_column($arrayName['canonList'], 'mapList') as $mList) {
if (isset($mList['ruleDesc'])) {
$ruleDesc[] = $mList['ruleDesc'];
}
else {
$ruleDesc = array_merge($ruleDesc, array_column($mList, 'ruleDesc'));
}
}
print_r($ruleDesc);
输出:
Array
(
[0] => this is a test description
[1] => this is a test description 3
[2] => this is a test description 2
[3] => this is a test description 5
)
我注意到,对于您之前的问题,您有很多未被接受但有效的答案。请阅读并接受那些确实解决了你问题的答案。有公认答案的问题对社区更有用,接受这些问题会奖励那些为你解决问题付出努力的人。