1

I've this 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);
}  

I need to insert a key in the array only if have value. For example, $jsonUPictore not always has a value and in that case I don't need to write that key.

Some help?

1
  • So you're saying that not all of the fields are always going to be present in the array, right? Commented Jun 29, 2012 at 16:45

2 Answers 2

4

You could use the array_filter function with or without a parameter:

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

Example:

$jsonUncompleted[] = array_filter( array(
  'id'=> $jsonUId, 'name'=> $jsonUName, 'description' => $jsonUDescription,
  'date' => $jsonUDate, 'status' => $jsonUStatus, 'picture' =>$jsonUPicture
));
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful, because without a filter parameter, it will filter out every falsy value like 0, "", false, etc.
0

If you are wanting to remove all NULL values from an array there's an easy way to do it using the array_filter function the last poster mentioned:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.