我有两个多维数组,称为$array和$array1
,键和值是动态的,我能够找到$array
和$array1
的array_diff()
,我想打印数组键作为表列名和数组值作为表值。我面临的真正问题是,我不能省略没有值的列。这里我给出的样本代码有硬编码的数组键和值。
<?php
error_reporting(0);
$array[0] = array("key1" => "valueNew", "key2" => "Array2", "key3" => "value3", "key4" => "value4");
$array[1] = array("key1" => "valuetwo", "key2" => "Array2", "key3" => "value3", "key4" => "value4");
$array[2] = array("key1" => "valueThree", "key2" => "Array2", "key3" => "value3", "key4" => "value4");
$array1[0] = array("key1" => "Array1", "key2" => "Array2", "key3" => "Array3", "key4" => "Array4");
$array1[1] = array("key1" => "Array1", "key2" => "Array2", "key3" => "Array3", "key4" => "Array4");
$array1[2] = array("key1" => "Array1", "key2" => "Array2", "key3" => "Array3", "key4" => "Array4");
for($i=0;$i<count($array);$i++){
$implode[$i]=array_diff($array[$i],$array1[$i]);
}
$arrayKeys=array_keys($array[0]);
?>
<table width="200" border="1">
<tr>
<?php
for($i=0;$i<count($arrayKeys);$i++){
?>
<th scope="col"><?php echo $arrayKeys[$i]; ?></th>
<?php
}
?>
</tr>
<tr>
<?php
for($i=0;$i<count($arrayKeys);$i++)
{
?>
<td><?php for($j=0;$j<count($implode);$j++)
{
echo $implode[$j][$arrayKeys[$i]]."<br>";
} ?></td>
<?php
}
?>
</tr>
</table>
使用array_map和array_filter函数
试试下面的代码代替你的for循环。
$res = array_map(function($a,$b){
return [array_filter(array_diff($a,$b))];
},$array,$array1);