在PHP数组的数组中计数匹配项
有一个这样的数组。我正在努力数一数所有的比赛。现在我正在使用在PHP数组的数组中计数匹配项,php,arrays,multidimensional-array,count,multiple-matches,Php,Arrays,Multidimensional Array,Count,Multiple Matches,有一个这样的数组。我正在努力数一数所有的比赛。现在我正在使用 Array ( [0] => Array ( [song] => More Than A Feeling [artist] => Not Boston [time] => 15:00 ) [1] => Array ( [song] => More Than A Feeling [
Array
(
[0] => Array
(
[song] => More Than A Feeling
[artist] => Not Boston
[time] => 15:00
)
[1] => Array
(
[song] => More Than A Feeling
[artist] => Boston
[time] => 11:20
)
[2] => Array
(
[song] => More Than A Feeling
[artist] => Boston
[time] => 15:23
)
)
这很好,但如果艺术家不匹配,它会计算歌曲数。我试图输出以下内容
array_count_values(array_column($arr, 'song'));
不知道从哪里开始。谢谢你的帮助 在一个简单的循环中手动执行。我将搜索
$songs
数组,并将元素添加到$songCounters
中,没有重复项。输出$songCounters
数组将同时包含歌曲和计数,其顺序是将计数作为歌曲的下一个元素
Array
(
[0] => Array
(
[song] => More Than A Feeling
[artist] => Not Boston
[count] => 1
)
[1] => Array
(
[song] => More Than A Feeling
[artist] => Boston
[count] => 2
)
)
代码如下:
[(song)(count)(song)(count)]
这是php。找到了另一个问题的答案。这对我有用
//Here is your input array
$songs = array(0 => array('song' => 'More Than A Feeling', 'artist' => 'Not Boston', 'time' => 0),
1 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0),
2 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0));
$songCounters = array(); //Initialize the output array
//Now lets go through the input array
foreach($songs as $song) {
//Prepare the current song
$currentSong = array('song' => $song['song'], 'artist' => $song['artist']);
//Get the index of the current song from $songCounters
$index = array_search($currentSong, $songCounters);
//Insert if not found
if ($index == false) {
array_push($songCounters, $currentSong);
array_push($songCounters, 1); //Next element is the counter
}
else {
$songCounters[$index + 1]++; //Increase the counter if found
}
}
print_r($songCounters);
}
这类工作。给了我一些工作。我试图将计数添加到原始歌曲数组中,而不是您的。它将计数放在一个单独的数组中。之后我将无法对数组进行排序。但谢谢,这可能会帮助我进一步。无论如何,您需要一个单独的数组来输出。这就是使用另一个数组执行此操作的原因。
$arr = array(0 => array('song' => 'More Than A Feeling', 'artist' => 'Not Boston', 'time' => 0),
1 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0),
2 => array('song' => 'More Than A Feeling', 'artist' => 'Boston', 'time' => 0));
$hash = array();
$array_out = array();
foreach($arr as $item) {
$hash_key = $item['song'].'|'.$item['artist'];
if(!array_key_exists($hash_key, $hash)) {
$hash[$hash_key] = sizeof($array_out);
array_push($array_out, array(
'song' => $item['song'],
'artist' => $item['artist'],
'count' => 0,
));
}
$array_out[$hash[$hash_key]]['count'] += 1;
var_dump($array_out);