仅将唯一值插入数组
我有一组值,我按照它们出现的顺序将其推入数组中
$valsArray = array();
//I process each value from a file (code removed for simplicity)
//and then add into the array
$valsArray[] = $val;
如何将其转换为关联数组,而不是只插入值(作为关联数组的 $key )如果它不存在。如果确实存在,则将其计数($关联数组的值
)增加 1。与我现在所做的相比,我正在尝试找到一种更有效的方法来处理这些值。
I have a set of values that I'm pushing into an array in the order they occur
$valsArray = array();
//I process each value from a file (code removed for simplicity)
//and then add into the array
$valsArray[] = $val;
How do I turn this into an associative array instead where the value gets inserted (as $key of associative array
) only if it doesn't exist. If it does exist increment its count ($value of associative array
) by 1. I'm trying to find a more efficient way of handling those values compared to what I'm doing now.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
$valsArray = array_unique($valsArray);
$valsArray = array_unique($valsArray);
当您循环遍历您的值时,您可以执行以下操作:
example:
将为您提供:
As you loop thru your values you can do the following:
example:
will get you:
应该为你做。新条目被添加为值为 1 的键,现有条目的值会递增。 @ 可以避免每次遇到错误时抛出 E_NOTICE新的价值。
should do it for you. New entries get added as a key with a value of 1, existing entries get their value incremented. The @ avoids an E_NOTICE being thrown every time this encounters a new value.
添加完成后,您不能直接
$valsArray = array_unique($valsArray);
吗?或者您需要按正确的顺序保存钥匙吗?Can't you just
$valsArray = array_unique($valsArray);
when you're done adding? Or do you need to keep the keys in correct order?尝试查看以下文档
http://www.php。 net/manual/en/function.array-count-values.php
Trying looking at the following documentation
http://www.php.net/manual/en/function.array-count-values.php