数组键为数字

时间:2016-05-19 11:42:04

标签: php arrays associative-array

我有一个数组$产品:

Array
(
    [0] => Array
        (
            [id] => 2488
            [va] => 1526
        )

    [1] => Array
        (
            [id] => 19512
            [va] => 286
        )
    [2] => Array
        (
            [id] => 123
            [va] => 286
        )
);

现在我要构建第二个键=> value array其中:

key => [va]
value => frequency of key in the first array

所以输出将是:

array(1526 => 1, 286 => 2)

我试过了:

$test = array();

foreach($products as $product) {
    $va = $product['va'];
    $test["$va"]++;
}

这样我收到很多“未定义的偏移量”,如何使用数字作为关联数组键?

3 个答案:

答案 0 :(得分:2)

首先必须先定义一个值,然后再增加它。没有你的行$ test [“$ va”] ++;尝试在每次执行时增加一个非现有值。尝试使用这种修改过的方法:

<?php

$products = [
    [ 'id' => 2488, 'va' => 1526 ],
    [ 'id' => 19510, 'va' => 286 ],
    [ 'id' => 19511, 'va' => 286 ],
    [ 'id' => 19512, 'va' => 286 ],
];

$test = [];
foreach($products as $product) {
    $va = $product['va'];
    $test[$va] = isset($test[$va]) ? ++$test[$va] : 1;
}

var_dump($test);

输出显然是:

array(2) {
  [1526] =>
  int(1)
  [286] =>
  int(3)
}

答案 1 :(得分:1)

使用array_columnarray_count_values函数的“单行”解决方案:

// $products is your initial array
$va_count = array_count_values(array_column($products, 'va'));

print_r($va_count);

输出:

(
    [1526] => 1
    [286] => 2
)

答案 2 :(得分:0)

您必须检查密钥是否存在,如果不存在,则将值设置为1,使用如下

$test = array();

foreach($products as $product) {
    $va = $product['va'];
    if(isset($test["$va"]))
    {
        $test["$va"]++;
    }
    else
    {
      $test["$va"]=1;
    }
}