我是新接触JSON和PHP的,我在清理这种类型的数组时遇到了问题。在这里,我认为可以工作,但我还不明白它为什么不工作
for ($i = 0; $i < count($items); $i++) {
if ($items[$i][] === null) {
unset($items[$i]['']);
}
}
[
{
"ticketNumber": Ha&51,
"qty": 0,
"title": "Wheat",
"price": 44.2,
"purchaseDate": null,
"date": null
},
{
"ticketNumber": H88i51,
"qty": 2,
"title": "Prince",
"price": 12.99,
"purchaseDate": null,
"date": null
}
]
发布于 2020-09-14 18:20:32
以下是一种方法:
<?php
$s = <<<eof
[{"ticketNumber": "Ha&51","qty": 0,"title": "Wheat", "price":
44.2,"purchaseDate": null,"date": null},{ "ticketNumber": "H88i51","qty":
2, "title": "Prince", "price": 12.99,"purchaseDate": null,"date": null}]
eof;
$m_json = json_decode($s, true);
$f = fn ($v): bool => $v !== null;
foreach ($m_json as $m_tick) {
$a[] = array_filter($m_tick, $f);
}
var_export($a);
就我个人而言,我不喜欢这样,因为您正在将不同类型的值传递给filter函数。对于强类型语言,这是不允许的。但另一种选择是枚举“良好”属性,因此在这种情况下它似乎是一个很好的折衷方案。
发布于 2020-09-14 18:02:17
您不需要循环,只需使用array_filter
<?php
$array = array(1 => "PHP code tester Sandbox Online", 2 => null);
print_r($array);
$arrayFiltered = array_filter($array);
print_r($arrayFiltered);
这是一个简短的example
https://stackoverflow.com/questions/63889507
复制相似问题