0

我有这个多维数组,我将其命名为“原始”:

$original=
array
  0 => 
    array
      'animal' => 'cats'
      'quantity' => 1
  1 => 
    array
      'animal' => 'dogs'
      'quantity' => '1'
  2 => 
    array
      'animal' => 'cats'
      'quantity' => '3'

但是,我想将内部数组与同一动物合并以生成这个新数组(结合数量):

$new=
array
  0 => 
    array
      'animal' => 'cats'
      'quantity' => 4
  1 => 
    array
      'animal' => 'dogs'
      'quantity' => '1'

我知道在 stackoverflow 上有类似的问题,但不够相似,我无法弄清楚如何使用这些问题必须应用于这个特定示例的反馈。是的,我知道在你们很多人看来我可能看起来很愚蠢,但请记住,曾经有一段时间你们也不知道使用数组的废话 :)

我试过下面的代码,但得到Fatal error: Unsupported operand types (Referring to line 11). 如果我得到那个错误消失,我不确定这段代码是否会产生我想要实现的目标。

$new = array();
foreach($original as $entity){
    if(!isset($new[$entity["animal"]])){
        $new[$entity["animal"]] = array(
            "animal" => $entity["animal"],
            "quantity" => 0,
        );
    }
    $new[$entity["animal"]] += $entity["quantity"];
}

所以,我不知道我在做什么,我真的可以从专家那里得到一些帮助。为了尝试提出一个非常明确的问题,这里是……我需要对代码进行哪些更改,以便将$original其转换为$new?如果我提供的代码完全错误,您能否提供一个替代示例来解决问题?另外,我唯一熟悉的语言是 PHP,所以请提供一个仅使用 PHP 的示例。

谢谢

4

3 回答 3

0

你很亲密。

$new[$entity["animal"]] += $entity["quantity"];

需要是

$new[$entity["animal"]]['quantity'] += $entity["quantity"];

在您的 if ( !isset [...] ) 行中,您将 $new[$entity['animal']] 设置为一个数组,因此您需要在尝试添加之前访问该数组的 'quantity' 字段新的数量值。

于 2013-03-30T03:50:04.293 回答
0

您的代码不起作用的原因之一是您使用动物名称作为数组索引,而不是在所需输出中使用的整数索引。

尝试这个:

$new = array(); // Desired output
$map = array(); // Map animal names to index in $new
$idx = 0; // What is the next index we can use

foreach ($original as $entity) {
  $animal = $entity['animal'];
  // If we haven't saved the animal yet, put it in the $map and $new array
  if(!isset($map[$animal])) {
    $map[$animal] = $idx++;
    $new[$map[$animal]] = $entity;
  }
  else {
    $new[$map[$animal]]['quantity'] += $entity['quantity'];
  }
}
于 2013-03-30T03:54:58.513 回答
0

这有效:

$new = array();
$seen = array();
foreach($original as $entity) {
  // If this is the first time we're encountering the animal
  if (!in_array($entity['animal'], $seen)) {
    $new[] = $entity;
    $seen[] = $entity['animal'];

  // Otherwise, if this animal is already in the new array...
  } else {
    // Find the index of the animal in the new array...
    foreach($new as $index => $new_entity) {
      if ($new_entity['animal'] == $entity['animal']) {
        // Add to the quantity
        $new[$index]['quantity'] += $entity['quantity'];
      }   
    }   
  }
}

您的示例使用动物名称作为索引,但实际索引只是一个整数。

但是,我认为如果它的格式是这样的,那么结果数组会更容易使用和阅读:

array('cats' => 4, 'dogs' => 1)

这将需要与上面不同但更简单的代码......但是,它不会直接回答您的问题。

于 2013-03-30T04:02:25.287 回答