我有以下数组:
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354
)
[3] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 357
)
在此数组标签中=>锦标赛重复两次,这是整个阵列的情况,许多标签重复两次,三次和很多次。 我希望这个数组显示为会有一个唯一的标签,每个数组中的tab_id都是不同的。这个tab_id被追加到唯一标签上。 最终的数组看起来应该是这样的。
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354 , 357
)
感谢。
答案 0 :(得分:1)
$arr = array(1 => array
(
entity_id => 5877,
parent_id => 5862,
label => Railbikes,
name => railbikes,
icon => books.svg,
level => 5,
tab_id => 353
),
2 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 354
),
3 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 357
)
);
print("<pre>");
foreach ($arr AS $key => $value){
/*foreach ($value AS $innerKey => $innerValue){
}*/
if($arr[$key]['label'] == $arr[$key-1]['label'] )
{
$newArr[$key-1]['tab_id'] = $arr[$key]['tab_id'].",". $arr[$key-1]['tab_id'];
}
else{
$newArr[$key]= $arr[$key];
}
}
print_r($newArr);
答案 1 :(得分:0)
如果entity_id总是相同,那么你可以“欺骗”一点:
$new_array = array();
foreach($array as $item)
{
if(!isset($new_array[$item['entity_id']]) $new_array[$item['entity_id']] = $item;
}
$new_array = array_values($new_array);
PS:总是试图阻止双重数据,不会让你的脚本更快;)
答案 2 :(得分:0)
试试这个
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$temp = $item;
$temp['tab_id'] = array( $item['tab_id'] );
$new_array[] = $temp;
$items[] = $temp['entity_id'];
}
else
{
$new_array[$check]['tab_id'][] = $item['tab_id'];
}
}
其中$array
是您向我们展示的原始数组。如果要在其余代码中保留相同的名称,可以在最后用$array = $new_array;
替换它。
此外,请注意,tab_id
现在是array
以符合您的要求。
如果您真的想保留它,请使用
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$new_array[] = $item;
$items[] = $item['entity_id'];
}
else
{
$new_array[$check]['tab_id'] .= ', '.$item['tab_id'];
}
}