2013-04-15 13 views
0

鑑於消息的相關聯的陣列(每個第二級陣列是不同的SQL查詢的結果):總長度平衡切削(如array_slice但對於相關聯的陣列)

$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

如果這是由數據庫查詢填充的,爲什麼不限制通過查詢返回的結果集呢?另外,如果這是關聯數組(不保證順序),你如何確定哪些值將被截斷?我也不知道爲什麼你的數據的結構是這樣的。看來你想截斷主陣列中不同子陣列的某些元素,但是怎麼做的邏輯還沒有弄清楚。在我看來,你的主要問題是找出一個更好的結構來表示你的數據(也許是一個對象?) –

+0

@MikeBrant在PHP中,assoc數組是排序的,否則如果排序的順序不能排序,ksort的作用是什麼?得到保證。 AFAIK對象方法/屬性不保證。 –

+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

然而,正如在上面所暗示的,如果這是從查詢的結果,你可以/應該可能重組您的查詢以提供更好的結果。

+1

你真的很酷。非常感謝你。 –

+0

我花了幾個小時,無法達到您的結果。但你做到了。 –