数组键作为数字

Array Key as number

我有一个数组 $products:

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

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

现在我要构建第二个键 => 值数组,其中:

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"]++;
}

这样我收到了很多"undefined offset",如何使用数字作为关联数组键?

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

$test = array();

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

您首先必须定义一个值,然后才能递增它。没有你的行 $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)
}

"One-line" 使用 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
)