我正在尝试使用php数组中的组显示值重复其中的次数。 示例:考虑该数组。 (json_encode输入)
[[6],[6],[6],[5,1],[3,3],[3,3],[3,2,1]]
结果,我需要的是一组数组以及它们的数量,如下所示:
[[6],3],
[[5,1],1],
[[3,3],2],
[[3,2,1],1],
任何类型?
EDIT
我尝试使用以下语句:
$result = array();
foreach ($myarray as $element) {
$result[$element[0]][] = $element;
}
但是我得到了这样的解决方案:
{"6":[[6],[6],[6]],"5":[[5,1]],"3":[[3,3],[3,3],[3,2,1]]}
问题出在3
组上,我需要分别将[3,3]和[3,2,1]分组。
答案 0 :(得分:3)
这似乎可以满足您的要求。
<?php
//This is your array of elements
$array = [[6],[6],[6],[5,1],[3,3],[3,3],[3,2,1]];
//This is a list of items that the program knows about, and their position
$known_items = array();
//For all the elements
foreach($array as $item){
//Sort the array to be in ascending order so that any combination will work
asort($item);
//We only want the item array to have values, and not keys
$item = array_values( $item );
//Make the content of this item a string so we can use it as a key in arrays
$arrString = json_encode( $item );
//Have we seen this item before?
if( array_key_exists( $arrString , $known_items ) ){
//Yes we have, increase the count
$known_items[ $arrString ][1]++;
} else {
//No we haven't. Add it and start the count as 1
$known_items[ $arrString ] = [ $item, 1 ];
}
}
echo json_encode( array_values( $known_items), JSON_PRETTY_PRINT);