我正在尝试将 4 个数组添加到一个数组 ($all_prices
) 中,然后根据 $all_prices
检查每个单独数组中每个键的值以确保他们是独一无二的。如果它们不是,我想在 if 的末尾添加一个 0
以使其唯一(因此 0.50
变为 0.500
)。
出于某种原因,尽管我已经将数据类型从 decimal 更改为 varchar,但我仍收到以下错误:
array_count_values(): Can only count STRING and INTEGER values!
编辑 这是 dd($all_prices) 的片段
array(4) { [0]=> array(9) { ["14.45"]=> string(8) "sample 1" ["12.40"]=>
string(8) "sample 2" ["14.13"]=> string(8) "sample 3" ["15.11"]=>
string(8) "sample 4"
代码:
$all_prices = [$list_a_prices, $list_b_prices, $list_c_prices, $list_d_prices];
$price_count = array_count_values($all_prices);
foreach($list_b_prices as $key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
我哪里错了?有没有办法将数据类型保留为 Decimal?
最佳答案
我认为您不应该以价格为索引,毕竟从数学的角度来看,5.0 和 5.00 根本没有区别。
如果您从数据库中获取值,您将在任何地方得到字符串。因此,您必须为键转换 (int)$key。
并且在您的 foreach 中,您正在更改一个临时变量。 $key 仅存在于循环的当前迭代中,您希望将其声明为:
foreach($list_b_prices as &(int)$key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
注意与号和整数转换。虽然我不确定哪个会先出现。但同样:我认为按一些不同的值编制索引会给你带来更好的结果。
关于php - 使用 array_count_values 并得到 "Can only count STRING and INTEGER values!"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166765/