Rumah > Soal Jawab > teks badan
Andaikan saya mempunyai tatasusunan seperti ini:
$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", ], ], ];
Saya ingin menapis tatasusunan ini supaya ia hanya mengandungi butiran di mana nilainya tidak kosong. type
值为空,因此它不应返回详细的 type
oleh Airco. Dalam kes ini, tatasusunan yang dikembalikan sepatutnya kelihatan seperti ini:
$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", ], ], ];
Saya tahu saya boleh menapis tatasusunan berdasarkan lajur kosong menggunakan kod berikut (seperti yang terdapat di sini):
$result = array_filter($array, function($o) use($column) { return trim( $o[$column] ) !== '' && $o[$column] !== null; });
Tetapi memandangkan saya mempunyai tatasusunan bersarangdetails
, saya tidak pasti cara menyesuaikan kod ini untuk menjadikannya berfungsi untuk kes saya.
P粉4587250402023-09-09 09:24:13
Milik andaarray_filter
仅在第一级起作用。您还希望在 details
数组上进行循环,您可以使用简单的 foreach 循环来完成此操作。外部循环将遍历所有行,内部循环将遍历每行的详细信息
.
<?php foreach($array as &$row){ foreach($row['details'] as $key => $record){ if(strlen($record['value']) == 0){ unset($row['details'][$key]); } } }