将php循环数据附加到JSON对象

时间:2019-02-12 19:53:43

标签: php json loops append

我需要在html模板中循环php数据,所以我知道它与JSON有关,但不是JSON专家,并且在搜索网络时找不到太多帮助。

$uniqueFranchise_id = array_unique($franchise_id);
$dataArr = '[
    {
        "name": "Dylan",
        "page_link": "https://mypage.com/"
    }
   ]';
foreach($uniqueFranchise_id as $franchise)
{
    $sqlFranchise = "select * from franchise where franchise_id = $franchise";
    $resultFranchise = $conn->query($sqlFranchise);
    if($resultFranchise->num_rows > 0)
    {
        while($rowFranchise = $resultFranchise->fetch_assoc())
        {
           $dataArr = json_decode($data, TRUE);
           $dataArr[] = "['name'=>'".$rowFranchise['name']."', 'page_link'=>'".$rowFranchise['page_link']."']";
           //$json = json_encode($dataArr);
        }
    }
}

$json = json_encode($dataArr);
print_r($dataArr);

但是它仅追加一行。实际上,它会删除dataArr中已经存在的数据,而仅从循环中添加一行?也许我正在把这种情况完全弄错了?

2 个答案:

答案 0 :(得分:2)

您将$ dataArr设置在while循环内。因此,每次循环运行时,它将被覆盖。另外,它更有意义,当您将其作为数组(或对象)进行处理并随后将其转换为JSON时,它会更加清晰。

$dataArr = array(array('name' => 'Dylan', 'page_link' => 'https://mypage.com/'));

foreach($uniqueFranchise_id as $franchise)
{
    $sqlFranchise = "select * from franchise where franchise_id = $franchise";
    $resultFranchise = $conn->query($sqlFranchise);
    if($resultFranchise->num_rows > 0)
    {
        while($rowFranchise = $resultFranchise->fetch_assoc())
        {
           $dataArr[] = array('name' => $rowFranchise['name'], 'page_link' => $rowFranchise['page_link']);
        }
    }
}

$json = json_encode($dataArr);
echo $json;

答案 1 :(得分:2)

您不应该自己构建字符串,应该构建数据,然后对结果进行JSON编码(代码中的注释)...

$dataArr = '[
    {
        "name": "Dylan",
        "page_link": "https://mypage.com/"
    }
   ]';
// decode existing JSON to start array
$dataArr = json_decode($data, TRUE);
foreach($uniqueFranchise_id as $franchise)
{
    // Read just the data you need from the table
    $sqlFranchise = "select name, page_link from franchise where franchise_id = $franchise";
    $resultFranchise = $conn->query($sqlFranchise);
    if($resultFranchise->num_rows > 0)
    {
        // Read all of the rows into an array
        $newData = $resultFranchise->fetch_all(MYSQLI_ASSOC);
        // Add in existing data
        $dataArr = array_merge($dataArr, $newData);
    }
}

// Now encode the list of elements into 1 string
echo json_encode($dataArr);

如果不信任此数据来停止SQL注入,还应该查看准备好的语句。