PHP数组:如何获得没有0值的数组

时间:2011-10-04 07:10:22

标签: php

如何使用大于0的[hits]提取或获取数组的值?

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
        )

)

4 个答案:

答案 0 :(得分:6)

假设> = PHP 5.3 ...

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

答案 1 :(得分: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);

答案 2 :(得分:1)

首先,它不是数组数组,而是对象数组。只需循环它们并进行条件检查。像这样:

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

答案 3 :(得分:1)

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

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

?>