Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/246.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何对php数组中的所有项运行sql查询_Php_Mysql_Mysqli_Retrofit - Fatal编程技术网

如何对php数组中的所有项运行sql查询

如何对php数组中的所有项运行sql查询,php,mysql,mysqli,retrofit,Php,Mysql,Mysqli,Retrofit,我的PHP脚本应该从API接收不确定数量的JSON数据,将其存储在数组中,然后对数组中的每个项运行SQL查询。然后将查询作为JSON对象返回 我的API如下所示: if($_POST(['id'])){ $id= $_POST['id']; foreach($value as $id){ $sql = "SELECT id, header, body FROM `messages` WHERE id= $id";

我的PHP脚本应该从API接收不确定数量的JSON数据,将其存储在数组中,然后对数组中的每个项运行SQL查询。然后将查询作为JSON对象返回

我的API如下所示:

if($_POST(['id'])){
    $id= $_POST['id'];
    foreach($value as $id){
        $sql = "SELECT id, header, body FROM `messages` WHERE id= $id";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $id);
        $stmt->execute();
        while ($row = mysqli_fetch_assoc($stmt)) {
            $response = $row ['id'];
            $response = $row ['header'];
            $response = $row ['body'];
        }
        $stmt->close();
    }

    return json_encode($response);
}
对我来说,这似乎效率很低,必须有一个SQL函数来检查数组中的所有变量

我需要我的JSON看起来像这样

{
    "resoponse": {
        "check": "check"
    },
    "code": [{
            "id": "id",
            "header": "header",
            "body": "body"
        },
        {
            "id": "id",
            "header": "header",
            "body": "body"
        },
        {
            "id": "id",
            "header": "header",
            "body": "body"
        }
    ]
}
我正在使用改型/gson将JSON返回到运行kotin的android应用程序,因此如果我遗漏了什么,请告诉我


谢谢您的时间。

此代码可能会帮助您

$id= $_POST['id'];
$resoponse = array();
$array_push = array();
// foreach($value as $id){
    $sql = "SELECT id, header, body FROM `messages` WHERE id= ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $id);
    $stmt->execute();
    while ($row = mysqli_fetch_assoc($stmt)) {
        $response['id'] = $row ['id'];
        $response['header'] = $row ['header'];
        $response['body'] = $row ['body'];
        $array_push[] = $response; 
    }
    $stmt->close();
// }

$return = array("resoponse"=>array("check"=>"check"),"code"=>$array_push);

return json_encode($return);

我真的不知道我在做什么。你要做的是将一个JSON对象转换成一个数组并循环遍历该数组

这个例子来自w3学校

$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';

$arr = json_decode($jsonobj, true);

foreach($arr as $key => $value) {
  echo $key . " => " . $value . "<br>";
}

如果它是一个ID集合,您可以在启动foreach循环$array\u push=array之前使用where in子句初始化数组\u push变量;