我有一长串包含值的数组。我正在尝试编写一个脚本,它将在数组中找到重复的键/值对并向我报告,因此我知道哪些数组具有相同的数据。
$array = array(
'one' => array('foo' => 'foo', 'baz' => 'baz', 'bar' => 'bar'),
'two' => array('foo' => 'foo', 'baz' => 'baz', 'nil' => 'nil'),
'three' => array('foo' => 'foo', 'var' => 'var'),
'four' => array('var' => 'var', 'nil' => 'nil'),
'five' => array('bar' => 'bar')
);
// First failed attempt
//call_user_func_array('array_intersect_assoc', $array));
结果应该能够识别2个或更多个数组共享相同的键和值。
array(
array(
'keys' => array('one', 'two', 'three'),
'values' => array('foo' => 'foo')
),
array(
'keys' => array('one', 'five'),
'values' => array('bar' => 'bar')
),
array(
'keys' => array('one', 'two'),
'values' => array('foo' => 'foo', 'baz' => 'baz')
),
array(
'keys' => array('three', 'four'),
'values' => array('var' => 'var')
),
array(
'keys' => array('two', 'four'),
'values' => array('nil' => 'nil')
),
);
处理这些数组的正确方法是什么?我怎样才能实现这样的目标呢?
答案 0 :(得分:2)
实际上,假设值始终是字符串,这很容易。
$master = array();
foreach($array as $name => $row)
{
foreach($row as $key => $value)
{
if(empty($master[$key.$value]))
{
$master[$key.$value] = array();
}
$master[$key.$value][] = $name;
}
}
print_r($master);