要将重复值合并到PHP中的多维数组中,代码如下-
<?php $my_arr = array( array('Age'=>23, 'name'=>'Joe', 'hobby'=>'Cycling'), array('Age'=>26, 'name'=>'Hannah', 'hobby'=>'Rowing'), array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling'), array('Age'=>30, 'name'=>'Dev', 'hobby'=>'Cycling') ); foreach($my_arr as $entry => $vals) { $new_vals[$vals['hobby']][]=$vals; } echo "唯一的数组元素是 "; print_r($new_vals); ?>
输出结果
唯一的数组元素是 Array ( [Cycling] => Array ( [0] => Array ( [Age] => 23 [name] => Joe [hobby] => Cycling ) [1] => Array ( [Age] => 30 [name] => Dev [hobby] => Cycling ) [2] => Array ( [Age] => 30 [name] => Dev [hobby] => Cycling ) ) [Rowing] => Array ( [0] => Array ( [Age] => 26 [name] => Hannah [hobby] => Rowing ) ) )
定义了一组值,这些值将age,name和hobby映射到某些值。“ foreach”循环用于遍历数组值,并将新值分配给数组中的一项。以前重复的值现在将合并到一个条目中,从而避免存储重复的值。