簡體   English   中英

在PHP中組合數組索引及其值

[英]Combine array index and their values in PHP

我有一個數組,具有要合並為一個數組的元素。 數組中的元素沒有特定的順序。 我正在使用PHP。

這就是我的意思。

//Input - I have this
array(
  0 => array(cat => 3),
  1 => array(dog => 4),
  2 => array(bug => 1),
  3 => array(bug => 5),
  4 => array(dog => 2),
  5 => array(dog => 1)

);

//Output - I want this 
//They are an accumulation of the values above
array(
   cat => 3,
   dog => 7,
   bug => 6

);

就像許多人說你不能在一個數組中擁有相同的鍵,你可以做的是:

//create samples
$item = array ();
$item['animal'] = 'cat';
$item['val'] = 10;

//build the array
$items = array ();
array_push ($items,$item);       
// assuming u have some items in the array now u can:
// assuming your array name is $items

$final_array = array ();

foreach ($items as $item)
{
    $final_array[$item['animal']]+=$item['val'];  
}

//the result is in $final_array

您可以使用array_reduce和一個閉包(在5.3或更高版本中有效)

$res = array_reduce($array, function (&$result, $val) {
      foreach ($val as $k=>$v){
           if (!isset($result[$k])) $result[$k] = 0;
           $result[$k]+= $val;
           return $result;
      }
}, array());

@Orangepill的答案實際上對我不起作用,並且很奇怪(減少時沒有返回值和按引用)。

這確實有效:

$in = array(
  array('cat' => 3),
  array('dog' => 4),
  array('bug' => 1),
  array('bug' => 5),
  array('dog' => 2),
  array('dog' => 1),
);

$out = array_reduce($in, function($out, $el) {
  @$out[ key($el) ] += reset($el); // Only 1 key + val per element?
  return $out;
}, array());

var_dump($out);

@是禁止顯示新密鑰的通知。 NULL + 2 = 2這樣就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM