[英]selected values from multidimensional array in php
I have the following array : 我有以下数组:
Array
(
[0] =Array(
[date] =2016-09-16
[data] = Array(
[0] =Array
(
[ID] =1945
[Debit] =CREDIT
[timestamp] =1474025139
[LastName] =test1
[FirstName] =test1
)
[1] =Array
(
[ID] =1946
[Debit] =CREDIT
[timestamp] =1474025140
[LastName] =test2
[FirstName] =test2
)
[2] =Array
(
[ID] =1947
[Debit] =CREDIT
[timestamp] =1474025130
[LastName] =test3
[FirstName] =test3
)
)
[start_date] =2016-09-16
[end_date] =2016-09-16
[show_fee] =0
)
[1] =Array
(
[date] =2016-09-15
[data] = Array
(
[0] =Array
(
[ID] =1955
[Debit] =CREDIT
[timestamp] =1474025159
[LastName] =test11
[FirstName] =test11
)
[1] =Array
(
[ID] =1956
[Debit] =CREDIT
[timestamp] =1474025150
[LastName] =test22
[FirstName] =test22
)
[2] =Array
(
[ID] =1957
[Debit] =CREDIT
[timestamp] =1474025150
[LastName] =test33
[FirstName] =test33
)
)
[start_date] =2016-09-16
[end_date] =2016-09-16
[show_fee] =0
)
)
Now i wanted to filter an array from the above array with specific keys. 现在我想用特定的键从上面的数组中过滤一个数组。 For example i want timestamp and id . 例如,我想要时间戳和id。 We can assume id/timestampd will be key and vice versa. 我们可以假设id / timestampd是关键,反之亦然。
I tried array_column but not succeeded. 我尝试了array_column但没有成功。
It's not easy to be sure of what you exactly need the output to be. 确定您确切需要的输出是不容易的。
A general principle might use the assumption that the following rules apply: 一般原则可以假设以下规则适用:
id
and timestamp
keyed values are the only ones kept in sub-arrays where they appear id
和timestamp
键值是出现在子数组中的唯一键值 Based on these rules, here is a general-purpose solution which works for any structure (and notably regardless of the depth-level where searched keys appear): 基于这些规则,这是一种通用解决方案,它适用于任何结构(尤其是与出现搜索键的深度级别无关):
function select($input) {
$keys = ['ID', 'timestamp'];
return is_array($input)
? (array_keys($intersect = array_intersect_key($input, array_flip($keys))) == $keys
? $intersect
: array_map('select', $input)
)
: $input;
}
$output = select($input);
The (tested) function uses the following approach: (已测试的)函数使用以下方法:
$input
, returns it as is if it's not an array 对于给定的$input
,如果它不是数组,则按原样返回 $input
and: 否则,在$input
查找搜索的键,然后:
$input
mapped by recursive call of the function for each of its items 否则返回通过递归调用函数为其每个项目映射的$input
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.