2011-01-30 374 views
0

如何以這種方式組合數組?合併數組(PHP)

來源:

Array 
(
    [0] => Array 
     (
      [id] => 3 
      [title] => book 
      [tval] => 10000 
     ) 
    [1] => Array 
     (
      [id] => 3 
      [title] => book 
      [tval] => 1700 
     ) 
    [3] => Array 
     (
      [id] => 27 
      [title] => fruit 
      [tval] => 3000 
     ) 

....... 

) 

結果:

Array 
(
    [0] => Array 
     (
      [id] => 3 
      [title] => book 
      [tval] => 10000,1700 
     ) 
    [1] => Array 
     (
      [id] => 27 
      [title] => fruit 
      [tval] => 3000 
     ) 
....... 

) 

請幫忙解決這個問題, 謝謝! 抱歉不好英語(

+0

嘗試`array_walk()`http://php.net/manual/en/function.array-walk.php – 2011-01-30 13:53:19

+0

請使用`var_export`而不是`print_r` – arnaud576875 2011-01-30 13:59:18

回答

3

這應該工作:

$result = array(); 
foreach($array as $elem) { 
    $key = $elem['id']; 
    if (isset($result[$key])) { 
     $result[$key]['tval'] .= ',' . $elem['tval']; 
    } else { 
     $result[$key] = $elem; 
    } 
} 

基本上,這組元素通過id,串聯tvals(由,分隔)

+0

謝謝!但它不能正常工作。 – Vadim 2011-01-30 14:16:44

0

只需user576875的方法略有建設:

$a = array (0 => array ('id' => 3, 
          'title' => 'book', 
          'tval' => 10000 
         ), 
      1 => array ('id' => 3, 
          'title' => 'book', 
          'tval' => 1700 
         ), 
      3 => array ('id' => 27, 
          'bcalias' => 'fruit', 
          'tval' => 3000 
         ) 
     ); 

$result = array(); 
foreach ($a as $elem) { 
    $key = $elem['id']; 
    if (isset($result[$key])) { 
     $result[$key]['tval'] .= ',' . $elem['tval']; 
    } else { 
     $result[$key] = $elem; 
    } 
} 
$result = array_merge($result); 

var_dump($result); 

給出結果:

array 
    0 => 
    array 
     'id' => int 3 
     'title' => string 'book' (length=4) 
     'tval' => string '10000,1700' (length=10) 
    1 => 
    array 
     'id' => int 27 
     'bcalias' => string 'fruit' (length=5) 
     'tval' => int 3000 

唯一的區別是array_merge()重置鍵