Maison > Questions et réponses > le corps du texte
Supposons que j'ai un tableau comme celui-ci :
$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", ], ], ];
Je souhaite filtrer ce tableau afin qu'il ne contienne que des détails dont la valeur n'est pas vide. Airco type
值为空,因此它不应返回详细的 type
. Dans ce cas, le tableau renvoyé devrait ressembler à ceci :
$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", ], ], ];
Je sais que je peux filtrer un tableau en fonction de colonnes vides en utilisant le code suivant (trouvé ici) :
$result = array_filter($array, function($o) use($column) { return trim( $o[$column] ) !== '' && $o[$column] !== null; });
Mais comme j'ai un tableau imbriquédetails
, je ne sais pas trop comment adapter ce code pour le rendre adapté à mon cas.
P粉4587250402023-09-09 09:24:13
Votrearray_filter
仅在第一级起作用。您还希望在 details
数组上进行循环,您可以使用简单的 foreach 循环来完成此操作。外部循环将遍历所有行,内部循环将遍历每行的详细信息
.
<?php foreach($array as &$row){ foreach($row['details'] as $key => $record){ if(strlen($record['value']) == 0){ unset($row['details'][$key]); } } }