0

I have an issue. I need to delete the element from JSON as per key value using PHP but its having some problem. I am explaining my code below.

<?php
$comment = json_encode(array(array('day_id' => '', 'comment' => ''),array('day_id' => '2', 'comment' => 'hello'), array('day_id' => '3', 'comment' => 'vodka3'),array('day_id'=>'','comment'=>'')));
$arrComment = json_decode($comment, true);
$imgarr=array();
for($i=0;$i<count($arrComment);$i++){
    if($arrComment[$i]['day_id']=='' && $arrComment[$i]['comment']==''){
        unset($arrComment[$i]);
    }
}
$arrComment=array_values($arrComment);
print_r($arrComment);
?>

Here when my multiple element key value is blank its not working. BUt if one single case its working. Here my need is if any of element day_id and comment is blank those element will remove from that json object and it will re-index again. Please help me.

2
  • It's NOT JSON, it's a PHP array. Commented Oct 19, 2016 at 7:26
  • 1
    @Rax Weber He just encode and decode it for better question. Commented Oct 19, 2016 at 7:27

1 Answer 1

2

After doing unset($arrComment[$i]); length of your array reduces. So, count($arrComment) is not 4 but 3. That's why your last element is not reached. To avoid this - use count() before starting the loop:

$cou = count($arrComment);
for($i=0; $i<$cou; $i++){
    if($arrComment[$i]['day_id']=='' && $arrComment[$i]['comment']==''){
        unset($arrComment[$i]);
    }
}

Or use for example array_filter:

$arrComment = array_filter(
    $arrComment,
    function($v) { return $v['day_id']!='' && $v['comment']!=''; }
);
print_r($arrComment);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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