[英]Count matches in array of arrays PHP
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'));
很好,但是如果歌手不匹配,它會計算歌曲數。 我正在嘗試輸出以下內容。
Array
(
[0] => Array
(
[song] => More Than A Feeling
[artist] => Not Boston
[count] => 1
)
[1] => Array
(
[song] => More Than A Feeling
[artist] => Boston
[count] => 2
)
)
不知道從哪里開始。 謝謝您的幫助!
在一個簡單的循環中手動進行操作。 我將搜索$songs
數組,並將元素添加到$songCounters
,沒有重復項。 輸出的$songCounters
數組將同時包含歌曲和計數,其順序是使計數成為歌曲的下一個元素。
[(song)(count)(song)(count)]
這是代碼:
//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);
這是php 小提琴 。
找到了另一個問題的答案。 這對我有用。
$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.