Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么array_filter的json呈现输出与foreach的输出不同?_Php_Json_Array Filter - Fatal编程技术网

Php 为什么array_filter的json呈现输出与foreach的输出不同?

Php 为什么array_filter的json呈现输出与foreach的输出不同?,php,json,array-filter,Php,Json,Array Filter,我偶然发现了一个模糊的bug,花了我很长时间才修复,我对它的潜在原因有点好奇。有人能解释一下我在使用array\u filter函数而不是简单的循环时看到的异常情况吗 我原以为以下两段代码会产生相同的结果: // original 'buggy' version $obj_to->ExtendedProperties[] = array_filter($extendedProperties, function($item){ return isset($item); }); // l

我偶然发现了一个模糊的bug,花了我很长时间才修复,我对它的潜在原因有点好奇。有人能解释一下我在使用
array\u filter
函数而不是简单的循环时看到的异常情况吗

我原以为以下两段代码会产生相同的结果:

// original 'buggy' version
$obj_to->ExtendedProperties[] = array_filter($extendedProperties, function($item){
  return isset($item);
});

// later, working version
foreach ($extendedProperties as $prop) {
  if (isset($prop)) $obj_to->ExtendedProperties[] = $prop;
}

然而,我当时发送结果的API没有考虑它们的等效输出,并返回了400的错误。我已经包括了不同json输出的示例。在一种情况下,我们在打印的json中看到一个数组标记,而在另一种情况下,我们没有看到

// 'good' json
"ExtendedProperties": [
  {
     "Name": "MaterialCode",
     "Value": "5450790E0LD048P8"
  },
...
相对于

// 'bad' json
"ExtendedProperties": {
  "0": {
      "Name": "PreferredDate",
      "Value": "2016-06-01"
  },
...

array\u filter
是返回数组,这就是为什么要使用array of array

我认为这是对的:

$obj_to->ExtendedProperties = array_filter($extendedProperties, function($item){
  return isset($item);
});
由于
array\u filter
保留了
$extendedProperties
数组中的数组键,因此会得到“坏”的json输出

因为ArayyFielter()保留密钥,所以即使原始数组有整数键,也可能会将得到的数组看作是关联数组,因为在密钥序列中可能有空洞。这意味着,例如,json_encode()将把结果数组转换为对象,而不是数组。对结果数组调用array_values(),以确保json_encode()为您提供一个数组


谢谢我错误地认为它会像javascript的filter()方法一样工作。看起来这是另一种阅读文档会有所帮助的情况。