0

我使用 JSON 将值从表单发送到数据库。我的表(表 tblstudent 的名称)有三列,即

    name                   score                               pic

["aa","bb","cc"]     ["525","523","562"]         ["img1.png","img2.png","img3.png"]

如何从 JSON 编码中获取值并将其放入 foreach 循环中以获得类似的结果

img1.png
aa
525

image2.png
bb
523

image3.png
cc
562

等等

4

2 回答 2

1

您可以使用 for 循环并通过键设置索引

  $name = ["aa","bb","cc"];
  $score = ["525","523","562"];
  $pic =  ["img1.png","img2.png","img3.png"];

  for($i = 0; $i < count($pic); $i++) {

    echo $pic[$i] . PHP_EOL;
    echo $name[$i] . PHP_EOL;
    echo $score[$i] . PHP_EOL;
    echo PHP_EOL;

  }

输出:

img1.png
aa
525

img2.png
bb
523

img3.png
cc
562
于 2020-10-18T04:07:25.557 回答
0

我尝试将index.php发送发布请求文件发送到文件request.php并将request.php数据发送到表单并将数据json_decode打印到文件。

索引.php

<!DOCTYPE html>
<html>
<head>
    <title>send request</title>
    <!--- jQuery cdn ----->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="display-data"></div>
</body>
</html>
<script type='text/javascript'>
    
    $(document).ready(function () {
        $.post('request.php', function (data, status) {
            if (status == 'success') {
                $('.display-data').append(data);
            }
        })
    });
    
</script>

请求.php

<?php

//This is a create a connection 
$servername = 'localhost';
$dbname = "stackoverflow";  
$username = "root";
$pass = "";

$conn = new PDO("mysql:host=$servername; dbname=$dbname;", "$username", "$pass");

//This is a create a connection end


$selectSql = "SELECT * FROM tblstudent";
$select = $conn->prepare($selectSql);
$select->execute();

for($i=0; $i<3; $i++) {
    $data = $select->fetch();
    
    $img[] = $data['image']; //This is a array of image
    $name[] = $data['name']; //This is a array of name
    $score[] = $data['score']; //This is a array of score
}

for($i=0; $i<3; $i++) {
    
    echo $img[$i]."<br>"; //Print data to index.php file
    echo $name[$i].'<br>'; //Print data to index.php file
    echo $score[$i]."<br>"; //Print data to index.php file
    echo '<br><br>';
}

?>
于 2020-10-18T14:42:47.600 回答