while循环与if语句不能正常工作

时间:2019-06-02 18:04:38

标签: php if-statement while-loop

嗨,我有以下while循环:

while ($row = mysqli_fetch_array($result2)){

    $elem_filho = $row['itempt_dim'];

    $marcas = "{name: " . "'" . $elem_filho . "'" . ", color: " . "'" . $cor_alea . "'" . ", size: 1";

    if (mysqli_num_rows($result2)) {
      $dif = "},";
    }

    else {
      $dif = "}]";
    }

    $vlk = $marcas . $dif;
    print_r($vlk);

  }

问题是我有类似的代码,它以这种方式工作,但是输出始终是},并且我希望查询的最后一项以}结尾。 我看不到我在做什么

预先感谢

1 个答案:

答案 0 :(得分:2)

使用json_encode,您的代码简化为:

$vlk = [];
while ($row = mysqli_fetch_array($result2)) {
    $vlk[] = [
        'name' => $row['itempt_dim'],
        'color' => $cor_alea,
        'size' => 1,
    ];
}
print_r(json_encode($vlk));