2011-04-06 150 views
0

我基本上需要找到一種方法來查看哪些產品的排序最多,然後返回前5個'post_id'的數組。複雜的PHP數組邏輯

這是一個包含產品細節不同階的數組:

Array 
(
    [1] => Array 
     (
      [post_id] => 1 
      [post_ident] => macbook_pro 
      [post_name] => Macbook Pro 
      [post_parent_ident] => rings 
      [post_cat_ident] => default 
      [post_module_ident] => store 
      [post_price] => 999.00 
      [post_currency] => EUR 
      [item_link] => index.php?module=store&show=post&category=default&parent=rings&post=macbook_pro 
      [qty] => 1 
     ) 

) 

Array 
(
    [1] => Array 
     (
      [post_id] => 1 
      [post_ident] => macbook_pro 
      [post_name] => Macbook Pro 
      [post_parent_ident] => rings 
      [post_cat_ident] => default 
      [post_module_ident] => store 
      [post_price] => 999.00 
      [post_currency] => EUR 
      [item_link] => index.php?module=store&show=post&category=default&parent=rings&post=macbook_pro 
      [qty] => 1 
     ) 

) 

Array 
(
    [1] => Array 
     (
      [post_id] => 1 
      [post_ident] => macbook_pro 
      [post_name] => Macbook Pro 
      [post_parent_ident] => rings 
      [post_cat_ident] => default 
      [post_module_ident] => store 
      [post_price] => 999.00 
      [post_currency] => EUR 
      [item_link] => index.php?module=store&show=post&category=default&parent=rings&post=macbook_pro 
      [qty] => 1 
     ) 

) 

如何確定哪些產品陣列中最?

例如,post_id 1的產品在數組中的3次。我如何計算,然後返回數組中的第一個項目的post_id?

+0

該數組來自SQL嗎? – thirtydot 2011-04-06 17:09:47

+0

不,產品詳細信息是序列化的,這是反序列化後的輸出。 – tmartin314 2011-04-06 17:11:34

回答

5
$result = array(); 
foreach($array as $value) 
{ 
    $postId = $value[1]['post_id']; 
    if(isset($result[$postId])){ 
     $result[$postId]++;  // increment count of post id if already exists in result 
    } 
    else{ 
     $result[$postId] = 1; // start count for post id 
    } 
} 

$keys = array_keys(asort($result)); // sort the array and find all the keys 
echo $keys[count($keys)-1];   // last key will be the answer