2014-09-24 72 views
-2
2個陣列

你好所以這是我例如數組:合併基於類似的值

[0] => Array 
( 
    [id] => 10 
    [count] => 10  
) 

[1] => Array 
    ( 
     [id] => 10  
     [count] => 20  
    ) 

[2] => Array 
    (
     [id] => 10 
     [count] => 30  
    ) 

我想通過ID這3個陣列併入1到這種格式: 陣列(ID =>'10 ',count =>('10','20','30')) 我有多個ID,每一個我想返回一個字符串,其格式爲「10,20,30等。 「有什麼想法嗎?

+1

那麼你有什麼嘗試?你在執行某些事情時遇到什麼問題?你有沒有至少嘗試過「蠻力」強制循環的方法? – 2014-09-24 19:37:04

+0

我被困在選擇具有相同id值的數組的最開始部分。一旦我選擇具有相同ID值的數組,我可以把最後一個數組放在一起... – nodejsj 2014-09-24 19:40:25

回答

0

如果妳窮舉使這串它可以做這樣的事情:

<?php 
    $source = [ 
     [ 
      'id' => 10, 
      'count' => 1, 
     ], 
     [ 
      'id' => 15, 
      'count' => 2, 
     ], 
     [ 
      'id' => 10, 
      'count' => 3, 
     ], 
     [ 
      'id' => 12, 
      'count' => 4, 
     ], 
     [ 
      'id' => 10, 
      'count' => 5, 
     ], 
    ]; 
    $output = []; 
    foreach($source as $arr) { 
     if (!isset($output[$arr['id']])) $output[$arr['id']] = ''; 
     $output[$arr['id']] .= $arr['count'].','; 
    } 
    var_dump($output); 

這裏唯一的一點是最後還有一個額外的,running example

+0

你在那裏試着用','op想要一個包含計數值的數組^^ – Dwza 2014-09-24 19:51:01

+0

OP表示他想要一個字符串......'我想要返回一個字符串,其格式爲「10,20,30等」..「' – DarkBee 2014-09-24 19:51:53

+0

哦,對不起,我猜這是通過我的觀點^^ – Dwza 2014-09-24 19:52:46

0

沒有搜索我想嘗試一些類似這樣的

foreach($source as $s){ 
    $dest[$s['id']]['count'][] = $s['count']; 
} 

在此之後,你可以通過implode(',', $array);

想有更好的方式比這:)

0

這恰好返回被請求的是什麼陣列(ID => '10',計數=>( '10','20' , '30'))

foreach($array as $x){ 
$newarray[$x["id"]][]=$x["count"]; 
} 
foreach($newarray as $id=>$count){ 
$c=implode(",",$count); 
$newnewarray[]=array("id"=>$id,"count"=>"($c)"); 
} 
print_r($newnewarray); 
0

下面是代碼不尾隨,

$result = array(); 

foreach($source as $s){ 
    if(!isset($result[$s['id']])) 
     $result[$s['id']] = $s['count']; 
    else 
     $result[$s['id']] .= ',' . $s['count']; 
} 
var_dump($result);