Reputation:
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.
Upvotes: 0
Views: 44
Reputation: 54796
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);
Upvotes: 2