php 为什么 array_diff() 给出 Array 到字符串转换错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19830585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:07:10  来源:igfitidea点击:

Why array_diff() gives Array to string conversion error?

phparraysmultidimensional-arrayarray-difference

提问by user2963765

I get array to string conversion error for the following line:

我收到以下行的数组到字符串转换错误:

$diff = array_diff($stockist, $arr);

Here, $arris an array decoded from a JSON file. Using the is_array()function I was able to verify that both parameters are arrays. Can someone point me the problem

$arr是一个从 JSON 文件解码的数组。使用该is_array()函数,我能够验证两个参数都是数组。有人能指出我的问题吗

$stockist = array();
while (!feof($file_handle)) {

    $line_of_text = fgetcsv($file_handle);
    $query = "SELECT * FROM reorderchart WHERE medicine = '"
        . trim($line_of_text[3])
        . "' ORDER BY medicine";
    $result = mysql_query($query);

    if (trim($line_of_text[2]) - trim($line_of_text[1]) <= 0) {

        while ($row = mysql_fetch_array($result)) {

            $file = "results.json";
            $arr = json_decode(file_get_contents($file),true);
            $pharmacy = trim($row['Medicine']);

            if (isset($stockist[$pharmacy])) {

                $medicine = $stockist[$pharmacy];
                $medicine[] = trim($row['Stockist']);
                $stockist[$pharmacy] = $medicine;

            } else {

                $medicine = array();
                $medicine[] = trim($row['Stockist']);
                $stockist[$pharmacy] = $medicine;
            }
        }
    }
}
$diff = array();
$diff = array_diff_assoc($stockist,$arr);
ksort($diff);
foreach ($diff as $key => $value) {

    echo "<table align='center' border='1'>";
    echo "<tr><td align = 'center'> <font color = 'blue'> $key</td></tr>";

    foreach($value as $key1 => $value1) {

        echo "<tr><td align ='center'>$value1</td></tr><br>";
    }
    echo "</table>";
}

回答by Viacheslav Kondratiuk

According to it:

根据它:

php -r 'array_diff(array("a" => array("b" => 4)), array(1));'
PHP Notice:  Array to string conversion in Command line code on line 1
PHP Stack trace:
PHP   1. {main}() Command line code:0
PHP   2. array_diff() Command line code:1

One of your arrays is multidimensional.

您的数组之一是多维的。

array_diffonly checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);

array_diff只检查 n 维数组的一维。当然,您可以使用以下方法检查更深的维度array_diff($array1[0], $array2[0]);

回答by E.A.T

Yes, the strict answer is because "One of your arrays is multidimensional."

是的,严格的答案是因为“你的一个数组是多维的。”

Another useful note might be - depending on your needs of further parsing the actual differences- consider first testing your arrays with:

另一个有用的注意事项可能是 -根据您进一步解析实际差异的需要- 考虑首先使用以下方法测试您的数组:

$diff = strcmp(json_encode($stockist), json_encode($arr));

or

或者

$diff = strspn(json_encode($stockist) ^ json_encode($arr), "
$diff = xdiff_string_diff(json_encode($stockist), json_encode($arr));
");

or

或者

while ($arr) {
  list($key, $value) = each($arr); 
  is_array($value) ? $arr = $value : $out[$key] = $value;
  unset($arr[$key]);
}
// Now $out is flatten version of $arr.

All these options will compare the entire array tree, not just the top level.

所有这些选项将比较整个数组树,而不仅仅是顶层。

回答by kenorb

Since array_diffcan only deals with one dimension, you can either:

由于array_diff只能处理一维,您可以:

  • 将您的多维数组转换为一维,例如:

    • 展平一个多维数组,例如:

      $results = array_diff(array_map('serialize',$a2), array_map('serialize',$a1)); 
      
    • 序列化数组,例如:

      function arrayRecursiveDiff($aArray1, $aArray2) { 
          $aReturn = array(); 
      
          foreach ($aArray1 as $mKey => $mValue) { 
              if (array_key_exists($mKey, $aArray2)) { 
                  if (is_array($mValue)) { 
                      $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]); 
                      if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; } 
                  } else { 
                      if ($mValue != $aArray2[$mKey]) { 
                          $aReturn[$mKey] = $mValue; 
                      } 
                  } 
              } else { 
                  $aReturn[$mKey] = $mValue; 
              } 
          } 
      
          return $aReturn; 
      }
      
  • 使用自定义递归array_diff类函数

回答by max

According to PHP documentation for the function

根据该函数的 PHP 文档

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same.

注意:当且仅当 (string) $elem1 === (string) $elem2 时才认为两个元素相等。换句话说:当字符串表示相同时。

For more information refer to http://php.net/manual/en/function.array-diff.php

有关更多信息,请参阅http://php.net/manual/en/function.array-diff.php

回答by Jim Wright

You can see in the array_diff() documentationthat:

您可以在array_diff() 文档中看到:

Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In other words: when the string representation is the same.

当且仅当 (string) $elem1 === (string) $elem2 时才认为两个元素相等。换句话说:当字符串表示相同时。

So it looks like you can't use this function with multi dimensional array, or in fact any value that cannot be converted to a string. This is because the function will cast values to a stringto do the comparison.

所以看起来你不能将此函数用于多维数组,或者实际上任何无法转换为字符串的值。这是因为该函数会将值转换为 astring来进行比较。

You can write your own function to recursively check arrays for a difference - in fact the following is from the comments of the docs linked above.

您可以编写自己的函数来递归检查数组的差异 - 事实上,以下内容来自上面链接的文档的评论。

You can see the comment here.

你可以在这里看到评论

$diff = strcmp(serialize($arr1), serialize($arr2))

回答by Trendfischer

I've got the same error and found the following bug report for php:

我遇到了同样的错误,并发现了以下 php 错误报告:

https://bugs.php.net/bug.php?id=60198

https://bugs.php.net/bug.php?id=60198

Some of the array_* functions that compare elements in multiple arrays do so by (string)$elem1 === (string)$elem2.

If $elem1 or $elem2 is an array, then the array to string notice is thrown.

Two examples of functions that can throw this are array_intersect() and array_diff().

If these functions are not expected to take arrays with other arrays as values, this should be mentioned on the documentation pages.

一些用于比较多个数组中元素的 array_* 函数是通过 (string)$elem1 === (string)$elem2 来实现的。

如果 $elem1 或 $elem2 是一个数组,则抛出数组到字符串通知。

可以抛出 this 的两个函数示例是 array_intersect() 和 array_diff()。

如果这些函数不希望将具有其他数组的数组作为值,则应在文档页面中提及。

That report describes, why php throws an error on comparing a multi-dimensional array.

该报告描述了为什么 php 在比较多维数组时会抛出错误。

回答by A. Fül?p

What about my solution:

我的解决方案呢:

$a1 = [
  'foo' => 'bar',
  'bar' => [
    'test' => 'test'
  ],
  'foobar' => 'fizzbuzz'
];

$a2 = [
  'foobar' => 'fizzbuzz',
  'herp' => [
    'derp' => 'herpderp'
  ]
];

$diff = array_diff(array_map('serialize', $a1), array_map('serialize', $a2));

$multidimensional_diff = array_map('unserialize', $diff);

print_r($multidimensional_diff);

回答by ZhuRenTongKu

Came across this one while working on a platform upgrade for PHP 7.3 from 5.3 today... Since I'm storing this value for use later on, I wanted to be sure I didn't wind up with a 'partially' serialized array that may break things downstream.

今天在为 PHP 7.3 从 5.3 进行平台升级时遇到了这个问题......因为我存储了这个值供以后使用,我想确保我没有得到一个“部分”序列化的数组可能会破坏下游的东西。

Thanks kenorb for getting me onto the right path (I upvoted ur answer). The following is working nicely for me.

感谢 kenorb 让我走上正确的道路(我赞成你的答案)。以下对我来说效果很好。

Code:

代码:

Array
(
    [foo] => bar
    [bar] => Array
        (
            [test] => test
        )

)

Output:

输出:

array_diff_assoc

回答by TheBlueAssasin

This is my solution for a similar problem. I want to compare two associative arrays and return the changed values, but some of the elements are arrays. So if I use

这是我对类似问题的解决方案。我想比较两个关联数组并返回更改后的值,但有些元素是数组。所以如果我使用

public static $example1 = [
    'id' => 1,
    'status' => 2,
    'elements' => ['test', 'example'],
    'different' => ['old' => 5, 'new' => 9]
];

public static $example2 = [
    'id' => 1,
    'status' => 3,
    'elements' => ['test', 'example'],
    'different' => ['old' => 5, 'new' => 8]
];

public static function test(){
    die(var_dump(self::udiffAssoc(self::$example1, self::$example2)));
}

public static function udiffAssoc(array $array1, array $array2)
{
    $checkDiff = function ($a, $b) use (&$checkDiff) {
        if (is_array($a) && is_array($b)) {
            return array_udiff_assoc($a, $b, $checkDiff);
        } elseif (is_array($a)) {
            return 1;
        } elseif (is_array($b)) {
            return -1;
        } elseif ($a === $b) {
            return 0;
        } else {
            return $a > $b ? 1 : -1;
        }
    };
    return array_udiff_assoc($array1, $array2, $checkDiff);
}

, it gives me "Array to string error". My function will also compare the elements which are arrays and if there's a difference, it will return the array element. It is still a work in progress and not tested extensively. For example:

,它给了我“数组到字符串错误”。我的函数还将比较数组元素,如果有差异,它将返回数组元素。它仍在进行中,尚未经过广泛测试。例如:

array(2) {
    ["status"]=>
    int(2)
    ["different"]=>
    array(2) {
    ["old"]=>
    int(5)
    ["new"]=>
    int(9)
  }
}

if you run ::test it will return:

如果您运行 ::test 它将返回:

##代码##