Php 数组键作为数字
我有一个数组$products:Php 数组键作为数字,php,arrays,associative-array,Php,Arrays,Associative Array,我有一个数组$products: Array ( [0] => Array ( [id] => 2488 [va] => 1526 ) [1] => Array ( [id] => 19512 [va] => 286 ) [2] => Array (
Array
(
[0] => Array
(
[id] => 2488
[va] => 1526
)
[1] => Array
(
[id] => 19512
[va] => 286
)
[2] => Array
(
[id] => 123
[va] => 286
)
);
现在我必须构建第二个key=>value数组,其中:
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"]++;
}
通过这种方式,我收到了很多“未定义的偏移量”,如何使用数字作为关联数组键?您必须检查键是否存在,如果不存在,则将值设置为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\u column
和array\u count\u value
函数的“一行”解决方案:
// $products is your initial array
$va_count = array_count_values(array_column($products, 'va'));
print_r($va_count);
输出:
(
[1526] => 1
[286] => 2
)
粘贴您的期望输出。您首先必须定义一个值,然后才能增加它。如果没有这一行,
$test[“$va”]++代码>尝试在每次执行时增加一个不存在的值。我已粘贴了所需的输出,那么downvote呢?我已尝试添加一个带有va“286”的新产品,该键的输出仍然为1。我刚刚注意到您的代码使用“+1”而不是“+”,我想知道为什么您的代码不适用于这个$products=[0=>['id'=>2488,'va'=>1526],1=>['id'=>19512,'va'=>286],2=>['id'=>19562,'va'=>286]@Jumpa抱歉,修复了明显的问题。我的错。很明显,你需要在作业前进行预激励。没问题,只是接受了你的答案,+1表示预激励。
(
[1526] => 1
[286] => 2
)