1

I have a problem in php. So, i have a json data which i will decode and put in object Then, i will use foreach function for gettings the parameters. I'll be putting this to a array so i can call it outside of the loop. However,when i'm displaying the results it returns a additional null value like this:

[{"mobile":"639179512744"},{"mobile":"639054971214"}, {"mobile":"639394297841"},{"mobile":"639296378818"},{"mobile":"639265161309"},{"mobile":null}]

Where the last record should not be included. I only have 5 records of mobile.

Here is my code:

$data = file_get_contents("php://input");
$data = (object)json_decode($data);
$model = $data->data;
$model = json_encode($model);
$model = json_decode($model);
$model = (object)$model;
foreach($model AS $row){
  $mobile = $row->mobile_number;
   $array[] = array(
          'mobile'=>$mobile
    );

}

echo json_encode($array);

And here is the data:

{"action":"upload","data":[{"mobile_number":"639179512744","sentdt":"2017-    02-07 00:21:57","imsi":"","remarks":"ACTIVE"},    {"mobile_number":"639054971214","sentdt":"2017-02-07     00:21:57","imsi":"","remarks":"ACTIVE"},    {"mobile_number":"639394297841","sentdt":"2017-02-07     00:21:57","imsi":"","remarks":"Absent Subscriber - No International Mobile     Subscriber Identity"},{"mobile_number":"639296378818","sentdt":"2017-02-07  00:21:58","imsi":"","remarks":"Absent Subscriber - No International Mobile  Subscriber Identity"},{"mobile_number":"639265161309","sentdt":"2017-02-07  00:21:58","imsi":"","remarks":"ACTIVE"},{}]}

Someone can help?I want to get rid of the additional null value Thanks

3 Answers 3

2

You could try doing a null check, like this:

foreach($model as $row){
  if (!is_null($row->mobile_number)) {
    $array[] = array(
      'mobile'=> $row->mobile_number;
    );
  }
}

Also note that there is no reason to cache $row->mobile_number in a variable, just pass it straight in to the array.

Sign up to request clarification or add additional context in comments.

Comments

1

This will solve your problem.

foreach($model AS $row){
  $mobile = $row->mobile_number;

  if(!empty($mobile) && isset($mobile)){      
     $array[] = array(
          'mobile'=>$mobile
     );
  }
}

Comments

0

Your end of data is:

...ACTIVE"},{}]}

When data decoded, the last of array value is empty object, that means last of array value not have member variable of mobile_number, so execute $row->mobile_number; can get value of null, and PHP error reporting will be reported a E_NOTICE error at the same time.

You can use function is_null() to filter null value, but you should be to check your data source at the same time.

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.