array_diff_assoc()参数#1不是数组php

时间:2016-11-30 13:43:51

标签: php arrays foreach associative-array

所以我有这个对象:

[
    {
        "id":1,
        "name":"create-users",
        "display_name":"Create user",
        "description":"Add new user"
    },
    {
        "id":2,
        "name":"edit-user",
        "display_name":"Edit user",
        "description":"Edit existing user"
    },
    {
        "id":3,
        "name":"create-post",
        "display_name":"Create post",
        "description":"create new post"
    },
    {
        "id":4,
        "name":"edit-post",
        "display_name":"Edit post",
        "description":"edit existing post"
    }
]

和另一个:

[
    {
        "id":3,
        "name":"create-post",
        "display_name":"Create post",
        "description":"create new post"
    },
    {
        "id":4,
        "name":"edit-post",
        "display_name":"Edit post",
        "description":"edit existing post"
    }
]

现在我在嵌套的foreach循环中循环遍历这两个对象top比较两个对象中的哪些数组是相等的(相等的键和值对)。

以下是foreach循环:

foreach ($role_perms as $role_perm) {
    foreach ($all_perms as $all_perm) {
        if (array_diff_assoc($all_perm, $role_perm)) {
            $all_perm['check'] = 1;
        }
    }
}

但我不知道为什么我一直收到错误

  

array_diff_assoc():参数#1不是数组   (在带有if语句的代码行上。)

我做错了吗?谢谢你的帮助

1 个答案:

答案 0 :(得分:1)

array_diff_assoc()用于比较数组。你的数据不是。

如果要使用array_diff_assoc()修改数据结构,以便拥有一个数组数组。例如:

$your_array = [
    [
        "id" => 3,
        "name"=>"create-post",
        "display_name"=>"Create post",
        "description"=>"create new post"
    ],
    [
        "id"=>4,
        "name"=>"edit-post",
        "display_name"=>"Edit post",
        "description"=>"edit existing post"
    ]
];

<强>编辑: 作为一种变通方法,将对象强制转换为数组,以防您无法修改数据结构。

   $object = new stdClass();
   $object->a = 'AAA';
   $object->b = 'BBB';

   var_dump((array) $object);

输出:

array(2) { ["a"]=> string(3) "AAA" ["b"]=> string(3) "BBB" }

在你的情况下:

foreach ($role_perms as $role_perm) {
    foreach ($all_perms as $all_perm) {
        if (array_diff_assoc((array) $all_perm, (array) $role_perm)) {
            $all_perm['check'] = 1;
        }
    }
}