这里我要比较两个数组。
我有两个表,一个是CATEGORY,第二个是USER(其中选择的多个类别以这种格式存储,)。
但是当USER想要在那时更新他们的类别时,先前选择的类别应该返回选中的1并且未选中的类别应该返回选中0并且这是我的代码。
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
这是我从数据库中获取的数组。
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
答案 0 :(得分:1)
这是为了处理与您提供的结构相同的结构。
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
如果有任何错误写了评论,我会修复它。