0

给定相关的消息数组(每个第二级数组是不同 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() 里面必须有什么?

4

1 回答 1

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

但是,正如上面所暗示的,如果这是来自查询的结果,您可以/应该可能重组您的查询以获得更好的结果。

于 2013-04-15T19:29:10.807 回答