PHP在数组内计数

时间:2014-04-14 10:43:21

标签: php arrays

我想创建一个列表,如果它已经在数组中添加到值+1。

当前输出

[1] => Array
    (
        [source] => 397
        [value] => 1
    )

[2] => Array
    (
        [source] => 397
        [value] => 1
    )

[3] => Array
    (
        [source] => 1314
        [value] => 1
    )

我想要实现的目标

[1] => Array
    (
        [source] => 397
        [value] => 2
    )

[2] => Array
    (
        [source] => 1314
        [value] => 1
    )

我目前正在沉溺于PHP

        foreach ($submissions as $timefix) {

              //Start countng
              $data = array(
                    'source' => $timefix['parent']['id'],
                    'value' => '1'
              );

              $dataJson[] = $data;

    }

            print_r($dataJson);

5 个答案:

答案 0 :(得分:2)

只需使用相关的数组:

$dataJson = array();

foreach ($submissions as $timefix) {
    $id = $timefix['parent']['id'];

    if (!isset($dataJson[$id])) {
        $dataJson[$id] = array('source' => $id, 'value' => 1);
    } else {
        $dataJson[$id]['value']++;
    }
}

$dataJson = array_values($dataJson); // reset the keys - you don't nessesarily need this

答案 1 :(得分:1)

这不完全是您想要的输出,因为不保留数组键,但如果它适合您,您可以使用项ID作为数组键。这样可以简化代码,无需循环使用已有的结果:

foreach ($submissions as $timefix) {
    $id = $timefix['parent']['id'];
    if (array_key_exists($id, $dataJson)) {
        $dataJson[$id]["value"]++;
    } else {
        $dataJson[$id] = [
            "source" => $id,
            "value" => 1
        ];
    }
}
print_r($dataJson);

答案 2 :(得分:0)

PHP有一个名为array_count_values的函数。可能你可以使用它

示例:

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

输出:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

答案 3 :(得分:0)

你应该自己简化一下。类似的东西:

<?
  $res = Array();
  foreach ($original as $item) {
    if (!isset($res[$item['source']])) $res[$item['source']] = $item['value'];
    else $res[$item['source']] += $item['value'];
  }
?>

在此之后,您将拥有数组$res,类似于:

Array(
  [397] => 2,
  [1314] => 1
)

然后,如果你真的需要指定的格式,你可以使用类似的东西:

<?
  $final = Array();
  foreach ($res as $source=>$value) $final[] = Array(
    'source' => $source,
    'value' => $value
  );
?>

答案 4 :(得分:0)

此代码将执行计数并生成$new数组,如示例中所述。

$data = array(
    array('source' => 397, 'value' => 1),
    array('source' => 397, 'value' => 1),
    array('source' => 1314, 'value' => 1),
);

$new = array();
foreach ($data as $item)
{
    $source = $item['source'];
    if (isset($new[$source]))
        $new[$source]['value'] += $item['value'];
    else
        $new[$source] = $item;
}
$new = array_values($new);