怎么计数数组

时间:2016-02-28 19:53:03

标签: php arrays count

如果有2个键的数组:

Array(
[0] => content
[1] => content
)

这是一项任务

如果是数组3键

Array(
[0] => content
[1] => content
[2] => content
)

这是其他任务

如何计算数组中有多少个键([0], [1] ..)?

我已经拥有了代码的所有结构,但只需要知道如何知道包含数组的变量中的键数量

2 个答案:

答案 0 :(得分:1)

private ArrayList<UserObject> tempUsers; public Utilities(){ tempUsers = new ArrayList<UserObject>(); } //reading file through BufferedReader and returns ArrayList of strings formatted like "1 1200" public ArrayList<String> ReadFile(){ BufferedReader reader = null; ArrayList<String> userStr = new ArrayList<String>(); try { File file = new File("file.edgelist"); reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { userStr.add(line); } return userStr; } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } //Where the problem actually lies public ArrayList<UserObject> BuildUsers(ArrayList<String> userStrings){ for (String s : userStrings){ String[] ids = s.split("\\s+"); UserObject exist = getUser(Integer.parseInt(ids[0])); if (exist == null){ //builds new UserObject if it doesn't exist in tempUsers UserObject newUser = new UserObject(Integer.parseInt(ids[0])); newUser.associate(Integer.parseInt(ids[1])); tempUsers.add(newUser); } else{ //otherwise adds "associate" Id to UserObject's AssociatesId collection exist.associate(Integer.parseInt(ids[1])); } } return tempUsers; } //helper method that uses Stream to find and return existing UserObject private UserObject getUser(int id){ if (tempUsers.isEmpty()) return null; try{ return tempUsers.stream().filter(t -> t.equals(new UserObject(id))).findFirst().get(); } catch (NoSuchElementException ex){ return null; } }

我认为这就是你要问的问题?

答案 1 :(得分:1)

根据您的评论,如果您使用array_count_values(),则会返回不包含相同值的数组。

$yourArr = array("content","content");
print_r( array_count_values($yourArr) );

<强>结果

array("content"=>2);

From W3School:

返回一个关联数组,其中键是原始数组的值,值是出现次数