首次发布海报,长期访客。
我试着在SO上找到一些可以帮助我的东西,但到目前为止我一直没有成功。如果有人知道这个问题的重复,我提前道歉,我找不到它。
不管怎样,我想知道是否有任何最佳实践或伟大的解决方案来解决我的问题。这并不是说我不能写一个正常工作的代码,我只是不喜欢每次都重写轮子,希望有一个优雅的解决方案。
考虑以下阵列:
Array
(
[0] => Array
(
[filename] => 'test1.jpg'
[comment] => 'This is a test'
[status] => 2
[author] => 'John Smith'
[uniquekey1] => 3
)
[1] => Array
(
[filename] => 'test2.jpg'
[comment] => 'This is a test'
[status] => 2
[author] => 'Unknown'
[uniquekey2] => 3
)
[2] => Array
(
[filename] => 'test3.jpg'
[comment] => 'This is a test'
[status] => 2
[author] => 'Unknown'
[uniquekey3] => 3
)
)
在处理完这个之后,我希望返回一个数组,它包含上面数组数组中的键,但只包含所有子数组中相同的键和值。实际上,上面会产生一个看起来像这样的数组:
Array
(
[comment] => 'This is a test'
[status] => 2
)
如图所示,只返回在所有三个(在本例中)数组项中相同的键:值对。
一个很好的使用示例是在iTunes中编辑多个项目,其中相等的值显示在编辑字段中,其余显示重影的"多个值"文本。我的目标是类似的。
感谢您的帮助和指点。
编辑:在此处也添加了解决方案。由于已接受的解决方案忽略了"uniqueKey"不相同这一点,因此出现了一些混乱,并且array_cintersect()在值匹配时也返回了这些值,这是不必要的行为。解决方案似乎是使用array_cintersect_assoc()
$a = array(
array(
'filename' => 'test1.jpg',
'comment' => 'This is a test',
'status' => 2,
'author' => 'John Smith',
'uniquekey1' => 3
),
array(
'filename' => 'test2.jpg',
'comment' => 'This is a test',
'status' => 2,
'author' => 'Unknown',
'uniquekey2' => 3
),
array(
'filename' => 'test3.jpg',
'comment' => 'This is a test',
'status' => 2,
'author' => 'Unknown',
'uniquekey3' => 3
),
);
$b = call_user_func_array('array_intersect_assoc',$a);
它看起来返回"comment"answers"status"字段,而不返回其他字段。
Array_intersection to the rescue:
$array = array();
$array[] = array('filename' => 'test1.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3);
$array[] = array('filename' => 'test2.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3);
$array[] = array('filename' => 'test3.jpg', 'comment' => 'This is a test', 'uniqueKey' => 3);
$intersection = call_user_func_array('array_intersect', $array);
$intersection则为:
Array
(
[comment] => This is a test
[uniqueKey] => 3
)