如果有2个键的数组:
Array(
[0] => content
[1] => content
)
这是一项任务
如果是数组3键
Array(
[0] => content
[1] => content
[2] => content
)
这是其他任务
如何计算数组中有多少个键([0], [1]
..)?
我已经拥有了代码的所有结构,但只需要知道如何知道包含数组的变量中的键数量
答案 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);
返回一个关联数组,其中键是原始数组的值,值是出现次数