【问题标题】:PHP/MySQL - how to push additional elements into array in the "while" loop?PHP/MySQL - 如何在“while”循环中将其他元素推送到数组中?
【发布时间】:2019-02-24 17:07:32
【问题描述】:

我正在从 mySQL 数据库中提取信息,但我需要添加数据库中没有的其他字段。

在启用注释选项之一之前,以下代码可以正常工作:

$sth =  mysqli_query($db_connect,$sql); 
while($r3 = mysqli_fetch_assoc($sth)) {
    //array_push($r3, 'str_close'=>$est_close_time);
    //$r3['str_close']=>$est_close_time;
    $row_v3_data[]=$r3;
}

启用后,php 显示“错误 500”

【问题讨论】:

  • 你的值没有在$row_v3_data[]数组中被替换???
  • 如果抛出错误 500,则大多数时间都会有一些内容写入服务器的错误日志。您可以搜索该消息并将其添加到问题中吗?
  • 站你检查答案了吗?
  • 问题已解决,谢谢大家!我只需要使用“=”而不是“=>”

标签: php mysql loops while-loop


【解决方案1】:

最简单的方法是将其他数据添加到$r3,然后再将其添加到数组中

$sth =  mysqli_query($db_connect,$sql); 
while($r3 = mysqli_fetch_assoc($sth)) {
    $r3['str_close'] = $est_close_time;
    $row_v3_data[]   = $r3;
}

这假设$est_close_time在使用之前确实存在

【讨论】:

  • 这个答案的单线变体,它取代了$r3['str_close'] = $est_close_time; $row_v3_data[] = $r3;。是 $row_v3_data[] = array('str_close' => $est_close_time, $r3) 或 PHP 5.4+ $row_v3_data[] = ['str_close' => $est_close_time, $r3];
  • 谢谢你的想法,我只是没想过用 "=" 代替 "=>" 。这完美!
  • 令人惊讶的部分是它被添加到数组 $r3 的末尾,但无论如何它都可以工作。
【解决方案2】:

您可以同时向关联数组添加键和元素。格式只是:

$r3['str_close'] = $est_close_time;

无需显式推送

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2017-09-16
    相关资源
    最近更新 更多