I have an issue while comparing two array and print result using php. I am explaining my code below.
$comment = json_encode(array(array('day_id' => '2', 'comment' => 'vodka1'), array('day_id' => '3', 'comment' => 'vodka2')));
$result = json_encode(array(array('day_id' => '1', 'restaurant' => '193'), array('day_id' => '2', 'restaurant' => '193'), array('day_id' => '3', 'restaurant' => '193')));
$arrComment = json_decode($comment, true);
$arrResult = json_decode($result, true);
foreach($arrResult AS $keyResult => $dataResult){
$day_id = $dataResult['day_id'];
$restaurant = $dataResult['restaurant'];
$strComment = '';
$getKey='';
$getKey = array_search($day_id, array_column($arrComment, 'day_id'));
if($getKey ==''){
$strComment = '';
}else{
$strComment = $arrComment[$getKey]['comment'];
}
$insertintodetails[]=array("day_id"=>$day_id,"rest"=>$restaurant,"comment"=>$strComment);
}
echo json_encode($insertintodetails);
Here i am getting the below result.
[{"day_id":"1","rest":"193","comment":""},{"day_id":"2","rest":"193","comment":""},{"day_id":"3","rest":"193","comment":"vodka2"}]
But my result should come like below.
[{"day_id":"1","rest":"193","comment":""},{"day_id":"2","rest":"193","comment":"vodka1"},{"day_id":"3","rest":"193","comment":"vodka2"}]
Here my requirement is if day_id from $result
is not present in $comment
then the respective comment field will remain blank. Please help me.
Try this solution it will work fine. here array_search()
always return key or boolean (http://php.net/manual/en/function.array-search.php).
So just need to check $getKey
is false or any key.
$comment = json_encode(array(array('day_id' => '2', 'comment' => 'vodka1'), array('day_id' => '3', 'comment' => 'vodka2')));
$result = json_encode(array(array('day_id' => '1', 'restaurant' => '193'), array('day_id' => '2', 'restaurant' => '193'), array('day_id' => '3', 'restaurant' => '193')));
$arrComment = json_decode($comment, true);
$arrResult = json_decode($result, true);
foreach($arrResult as $keyResult => $dataResult){
$day_id = $dataResult['day_id'];
$restaurant = $dataResult['restaurant'];
$strComment = '';
$getKey='';
$getKey = array_search($day_id, array_column($arrComment, 'day_id'));
if(is_numeric($getKey)){
$strComment = $arrComment[$getKey]['comment'];
}else{
$strComment = '';
}
$insertintodetails[]=array("day_id"=>$day_id,"rest"=>$restaurant,"comment"=>$strComment);
}
echo json_encode($insertintodetails);