PHP数组:我怎样才能得到没有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
)
)
答
首先它不是数组的数组,而是数组的对象。只要循环他们,并进行有条件检查。像这样:
<?php
$with_hits = array();
foreach ($objects as $object){
if ($object->hits > 0){
$with_hits[] = $object;
}
}
?>
答
您可以使用array_walk
或array_map
功能测试hits
。
$hits = array();
function fill_hits($key, $item)
{
global $hits;
if ($item->hits > 0) $hits[] = $obj;
}
array_walk('fill_hits', $array);
答
假设> = PHP 5.3 ...
$newArr = array_filter($arr, function($obj) {
return $obj->hits > 0;
});
+0
参数需要交换。 –
+0
Offtopic:只有少数编辑支持回叫... –
答
<?php
$ret = array();
foreach($data as $key => $obj) {
if($obj->hits > 0) {
$ret[$key] = $obj;
}
}
print_r($ret); // your filtered data here
?>
@stereorog:我同意,还要检查['printf()的'变换器](HTTP://键盘。 viper-7.com/eVhuuJ)[hakre](http://stackoverflow.com/users/367456/hakre)。 – alex