这是我的阵列。如果存在重复,我需要连接数组值。
Array
(
[0] => Array
(
[id] => 3
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[1] => Array
(
[id] => 6
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[2] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
以下是我的代码,它没有连接唯一值。
$conct= array();
foreach ($myArray as $array)
{
foreach ($array as $key => $value)
{
if ( ! isset($merged[$key]))
{
$conct[$key] = $value;
}
else
{
$conct[$key] .= ",".$value;
}
}
}
这是给我的。
Array
(
[0] => Array
(
[id] => 3,6,7
[location_id] => 2,2,1
[location_name] => 1st Floor,1st Floor,Ground Floor
[type] => 1,1,1
)
)
我需要根据唯一 location_id
和location_name
来结算这些值。
我的结果数组应该是。
Array
(
[0] => Array
(
[id] => 3,6
[location_id] => 2,2
[location_name] => 1st Floor,1st Floor
[type] => 1,1
)
[1] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
如何实现这一目标?
答案 0 :(得分:2)
试试这个..
<?php
$new_values = array();
$values = array(
array('id'=> 1, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 6, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 7, 'location_id' => 1, 'location_name' => 'Gound Floor','type'=>1),
);
foreach($values as $value) {
if(isset($new_values[$value['location_id']])) {
$temp = $new_values[$value['location_id']];
$temp['id'] .= ',' . $value['id'];
$temp['location_id'] .= ',' . $value['location_id'];
$temp['location_name'] .= ',' . $value['location_name'];
$temp['type'] .= ',' . $value['type'];
$new_values[$value['location_id']] = $temp;
} else {
$new_values[$value['location_id']] = $value;
}
}
$new_values = array_values($new_values);
print_r($new_values);
?>
输出:Array ( [0] => Array ( [id] => 1,6 [location_id] => 2,2 [location_name] => 1st Floor,1st Floor [type] => 1,1 ) [1] => Array ( [id] => 7 [location_id] => 1 [location_name] => Gound Floor [type] => 1 ) )
答案 1 :(得分:2)
$input = array(array('id'=>3,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>6,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>7,'location_id'=>1,'location_name'=>'Ground Floor','type'=>1)
);
$conct = array();
foreach($input as $k => $_input) {
foreach($_input as $key => $value) {
if(isset($conct[$key])) {
if(check_duplicate($duplicate,$input[$k])) {
$conct[$key] .= ",".$value;
} else {
$new[$key] = $value;
}
}
else
{
$conct[$key] = $value;
if($key=='location_id'||$key=='location_name')
$duplicate[$key] = $value;
}
}
}
function check_duplicate($duplicate=array(),$input=array()) {
foreach($duplicate as $dupe) {
if($dupe===$input['location_id'] || $dupe === $input['location_name'] )
return true;
else
return false;
}
}
echo "<pre>"; print_r($conct);
echo "<pre>"; print_r($new);