"Radiator","details"=>0=>["label"=>"Condition","value"=>"New",],1=>[""> 如何根据嵌套数组中的列过滤多维数组?-PHP中文网问答
如何根据嵌套数组中的列过滤多维数组?
P粉004287665
P粉004287665 2023-09-08 13:16:28
0
1
435

假设我有一个如下所示的数组:

$array = [ 0 => [ "label" => "Radiator", "details" => 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], 1 => [ "label" => "Airco", "details" => 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "", ], ], 2 => [ "label" => "Refrigerator", "details" => 0 => [ "label" => "Condition", "value" => "Bad", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ];

我想过滤这个数组,所以它只包含值不为空的详细信息。 Airco 的type值为空,因此它不应返回详细的type。在这种情况下,返回的数组应如下所示:

$array = [ 0 => [ "label" => "Radiator", "details" => 0 => [ "label" => "Condition", "value" => "New", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], 1 => [ "label" => "Airco", "details" => 0 => [ "label" => "Condition", "value" => "New", ], ], 2 => [ "label" => "Refrigerator", "details" => 0 => [ "label" => "Condition", "value" => "Bad", ], 1 => [ "label" => "Type", "value" => "Wall", ], ], ];

我知道我可以使用以下代码(如此处找到的)基于空列过滤数组:

$result = array_filter($array, function($o) use($column) { return trim( $o[$column] ) !== '' && $o[$column] !== null; });

但是由于我有一个嵌套数组details,我不太确定如何调整此代码以使其适合我的情况。

P粉004287665
P粉004287665

全部回复 (1)
P粉458725040

您的array_filter仅在第一级起作用。您还希望在details数组上进行循环,您可以使用简单的 foreach 循环来完成此操作。外部循环将遍历所有行,内部循环将遍历每行的详细信息

 $record){ if(strlen($record['value']) == 0){ unset($row['details'][$key]); } } }

现场演示

    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!