开发者

Merge arrays (PHP)

开发者 https://www.devze.com 2023-02-07 07:11 出处:网络
How com开发者_如何学Gobine arrays in this way? source: Array ( [0] => Array ( [id] => 3 [title] => book

How com开发者_如何学Gobine arrays in this way?

source:

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
       )

.......

)

result:

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

) 

please help to solve this problem, thanks!!! sorry for bad english(


This should work:

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

This basically groups elements by id, concatenating tvals (separated by ,).


Simply building slightly on user576875's method:

$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);

gives a result of:

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

The only real difference is the array_merge() to reset the keys

0

精彩评论

暂无评论...
验证码 换一张
取 消