给定关联的消息数组(每个第二级数组是不同sql查询的结果):
$tmp = array(
'type1'=>array ('key'=>'value'),
'type2'=>array(1=>1,2=>2,3=>3,4=>'men',5=>'pro'),
'type3'=>array(1=>1,2=>2,3=>3,'test'=>'website','creation'=>'www.prost.pro',8,9,10=>array('3dlevel','subarray'),11,12,13,14,15,16,18,18,19,20),
'type4'=>array(1,2,3)
);
我只需要显示其中的8个。 它们必须代表所有类型(第一级值)的消息。
所以我需要打电话:
$total_quantity_limit = 8;
var_dump(array_assoc_truncate($tmp, $total_quantity_limit));
得到类似的东西:
array(
'type1'=>array('key'=>'value'),
'type2'=>array(1=>1,2=>2,3=>3),
'type3'=>array(1=>1,2=>2),
'type4'=>array(1,2)
);
array_assoc_truncate()中必须包含什么内容?
答案 0 :(得分:1)
从我看到的示例输出中,看起来像你想要的东西:
<?php
$tmp = array(
'type1'=>array('key'=>'value'),
'type2'=>array(1=>1,2=>2,3=>3,4=>'men',5=>'pro'),
'type3'=>array(1=>1,2=>2,3=>3,'test'=>'website','creation'=>'www.prost.pro',8,9,10,11,12,13,14,15,16,18,18,19,20),
'type4'=>array(1,2,3)
);
function array_assoc_truncate($array, $limit){
$depth = 0;
$count = 0;
$out = array();
//outter loop
while($count < $limit){
//boolean, was a key found
$found = false;
//loop through each top level key
foreach($array as $k=>$v){
//if the value is an array
if(is_array($v)){
//get the keys
$keys = array_keys($v);
//if a keys exists at this depth
if(isset($keys[$depth])){
//get the key
$key = $keys[$depth];
//if $out doesn't have the top level key yet, add it
if(!isset($out[$k])){
$out[$k]=array();
}
//set the value under $key in $out
$out[$k][$key]=$v[$key];
//increment our count
$count++;
//a key was found at this depth
$found=true;
}
}
//if we hit our limit, break
if($count >= $limit){
break;
}
}
//if no key was found at this depth, there is no more depth to search
if(!$found){
break;
}
//go down one more level
$depth++;
}
//return the output array
return $out;
}
echo '<hr><h1>Before:</h1>';
var_dump($tmp);
echo '<hr><h1>After:</h1>';
adump(array_assoc_truncate($tmp, 8));
http://codepad.viper-7.com/a8cF5J
但是,正如上面所暗示的,如果这是来自查询的结果,您可能/应该重新构建查询以获得更好的结果。