gpt4 book ai didi

php - 连接数组值,如果包含重复项 - php

转载 作者:行者123 更新时间:2023-11-29 04:40:51 24 4
gpt4 key购买 nike

这是我的数组。如果存在重复项,我需要连接数组值。

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
)


)

我需要根据 unique location_idlocation_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
)


)

如何实现?

最佳答案

试试这个..

<?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] => 数组 ( [id] => 7 [location_id] => 1 [location_name] => 地下层 [type] => 1 ) )

关于php - 连接数组值,如果包含重复项 - php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29142305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com