2011-10-04 57 views
0

如何提取或得到大於0的[點數]數組的值?PHP數組:我怎樣才能得到沒有0值的數組

Array 
(
    [0] => stdClass Object 
     (
      [hits] => 0 
      [date] => 2011-09-29 17:58:25 
     ) 
    [1] => stdClass Object 
     (
      [hits] => 1 
      [date] => 2011-09-29 16:55:42 
     ) 

    [2] => stdClass Object 
     (
      [hits] => 1 
      [date] => 2011-09-29 17:54:38 
     ) 

    [3] => stdClass Object 
     (
      [hits] => 1 
      [date] => 2011-09-29 17:58:25 
     ) 
    [4] => stdClass Object 
     (
      [hits] => 0 
      [date] => 2011-09-29 17:58:25 
     ) 
    [5] => stdClass Object 
     (
      [hits] => 3 
      [date] => 2011-09-29 17:58:25 
     ) 

) 
+0

@stereorog:我同意,還要檢查['printf()的'變換器](HTTP://鍵盤。 viper-7.com/eVhuuJ)[hakre](http://stackoverflow.com/users/367456/hakre)。 – alex

回答

1

首先它不是數組的數組,而是數組的對象。只要循環他們,並進行有條件檢查。像這樣:

<?php 
$with_hits = array(); 
foreach ($objects as $object){ 
    if ($object->hits > 0){ 
    $with_hits[] = $object; 
    } 
} 
?> 
1

您可以使用array_walkarray_map功能測試hits

$hits = array(); 

function fill_hits($key, $item) 
{ 
    global $hits; 
    if ($item->hits > 0) $hits[] = $obj; 
} 

array_walk('fill_hits', $array); 
6

假設> = PHP 5.3 ...

$newArr = array_filter($arr, function($obj) { 
    return $obj->hits > 0; 
}); 
+0

參數需要交換。 –

+0

Offtopic:只有少數編輯支持回叫... –

1
<?php 
$ret = array(); 
foreach($data as $key => $obj) { 
    if($obj->hits > 0) { 
     $ret[$key] = $obj; 
    } 
} 

print_r($ret); // your filtered data here 

?> 
相關問題