从与另一个数组匹配的数组中取消设置值

时间:2018-02-14 17:57:45

标签: php arrays multidimensional-array array-intersect

确保$ config ['b']中没有设置匹配$ config ['a']的值的最快最有效的方法是什么?

在这种情况下,星期日14应该从$ config ['b'] ['小时'] ['星期日']取消。

$duplicates = array_intersect($config['a']['Hours'], $config['b']['Hours']);

给我一​​个错误,“注意:数组到字符串转换”,结果不正确,所以我的数组构造不正确或者我的方法不正确。

这是数组;

    $config  =  array(
                "a" => array(
                    "Hours" => array(
                        "Sunday" => array(12,13,14,15,16),
                    ),
                ),
                "b" => array(
                    "Hours" => array(
                        "Sunday" => array(0,1,2,3,4,5,6,7,8,9,10,11,14,17,18,19,20,21,22,23),
                        "Monday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Tuesday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Wednesday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Thursday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Friday" => array(0,1,2,3,4,5,19,18,19,20,21,22,23),
                        "Saturday" => array(0,1,2,3,4,5,8,19,20,21,22,23,24),
                    ),
                ),
            );

2 个答案:

答案 0 :(得分:2)

array_intersect无法递归工作,如文档中所述:https://secure.php.net/array_intersect

它迭代并将值作为字符串进行比较,从而将错误,因为它尝试将值array(12,13,14,15,16)用作字符串并失败。

在您的情况下,正确的方法是首先使用array_keys()比较密钥,然后使用array_intersect()array_diff()比较现有密钥。

修改

此示例应以所需方式工作:

$duplicateKeys = array_intersect(array_keys($config['a']['Hours']), array_keys($config['b']['Hours']));
$duplicates = [];

if(!empty($duplicateKeys) && is_array($duplicateKeys)) {
    foreach($duplicateKeys as $key) {
        $duplicates[$key] = array_intersect($config['a']['Hours'][$key], $config['b']['Hours'][$key]);
    }
}

答案 1 :(得分:0)

要从数组b中删除相应的' a',请使用array_diff函数

foreach($config['a']["Hours"] as $k => $v) { 
      $config['b']["Hours"][$k] = array_diff( $config['b']["Hours"][$k], $v);
    }