在关联数组中插入值,但前提是有值


Insert values in an associative array but only if have value

我有这个bucle:

foreach($jsonU as $j) {
        $jsonUId = $j->id;
        $jsonUName = $j->name;
        $jsonUDescription = $j->description;
        $jsonUDate = $j->date;
        $jsonUStatus = $j->status;
        $jsonUPicture = $j->picture;
        $jsonUncompleted[] = array('id'=> $jsonUId, 'name'=> $jsonUName, 'description' => $jsonUDescription, 'date' => $jsonUDate, 'status' => $jsonUStatus, 'picture' =>$jsonUPicture);
}  

只有当有值时,我才需要在数组中插入一个键。例如,$jsonUPictore并不总是有一个值,在这种情况下,我不需要编写该键。

一些帮助?

您可以使用带或不带参数的 array_filter 函数:

http://www.php.net/manual/en/function.array-filter.php

例:

$jsonUncompleted[] = array_filter( array(
  'id'=> $jsonUId, 'name'=> $jsonUName, 'description' => $jsonUDescription,
  'date' => $jsonUDate, 'status' => $jsonUStatus, 'picture' =>$jsonUPicture
));

如果你想从数组中删除所有NULL值,有一种简单的方法可以使用上一张海报提到的array_filter函数来完成:

$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');

来源: http://briancray.com/posts/remove-null-values-php-arrays/