【问题标题】:array_diff_assoc() argument #1 is not an array phparray_diff_assoc() 参数 #1 不是数组 php
【发布时间】:2016-11-30 13:43:51
【问题描述】:

所以我有这个对象:

[
    {
        "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 循环中遍历这两个对象,顶部比较这两个对象中的哪些数组是相等的(相等的键和值对)。

这里是 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 语句的代码行上。)

我做错了吗?感谢您的帮助

【问题讨论】:

  • var_dump($all_perm, $role_perm);
  • 你混淆了“数组”和“对象”。
  • @arkascha 请你澄清一下。前两个我称为对象,我认为它们是包含数组的对象?这是我混淆的地方吗?
  • 您发布的代码都是一个数字索引数组,其中包含一些对象。这些对象中的每一个显然都包含一些命名属性。您想找出对象的类,这将比通用处理更容易使用。
  • 您发布了一些 PHP 代码和一些 JSON 数据,顺便说一句,它们是 Javascript。您没有发布如何将 JSON 解码为 PHP 数据结构。看看json_decode()的文档,正确使用它(即传递TRUE作为它的第二个参数),错误就会消失。

标签: php arrays foreach associative-array


【解决方案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;
        }
    }
}

【讨论】:

  • 抱歉,我没有详细说明。我提供的数据是我手动编写的,但它实际上是从数据库中记录的。这是否意味着从数据库返回的值不是数组类型?再次抱歉,这可能没有意义,因为我是 php 的初学者?
  • 如果您无法修改原始数据结构,作为一种解决方法,您可以在使用 array_diff_assoc() 之前将对象转换为数组。我在答案中添加了一个示例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多