我在使用php比较两个数组和打印结果时遇到了问题。我在下面解释我的代码。
$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);
我在这里得到以下结果。
[{"day_id":"1","rest":"193","comment":""},{"day_id":"2","rest":"193","comment":""},{"day_id":"3","rest":"193","comment":"vodka2"}]
但我的结果应该如下所示。
[{"day_id":"1","rest":"193","comment":""},{"day_id":"2","rest":"193","comment":"vodka1"},{"day_id":"3","rest":"193","comment":"vodka2"}]
此处我的要求是,如果day_id from $result
中不存在$comment
,则相应的评论字段将保持空白。请帮帮我。
答案 0 :(得分:0)
试试这个解决方案它会正常工作。这里array_search()
总是返回键或布尔值(http://php.net/manual/en/function.array-search.php)。
所以只需要检查$getKey
是否为假或任何密钥。
$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);