dongzhi4073 2016-06-05 21:53
浏览 25

将静态数组替换为查询结果

Please see the php function below. I am trying to get the results of my query to display as an array in the same format as the static array shown below. How would I replace that static array with results from my query? Thanks in advance.

<?php
$mysqli = new mysqli("xxx", "xxx", "xxx", "xxx");

/* check connection */
if ($mysqli->connect_errno) {
    printf("Connect failed: %s
", $mysqli->connect_error);
    exit();
}

$query = "SELECT event_id, event_name FROM events ORDER by event_id";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_BOTH);

function get_price($find){
    $books=array(
        "java"=>266,
        "c"=>250,
        "php"=>320
        );

    foreach($books as $book=>$price)
    {
        if($book==$find)
        {
            return $price;
            break;
        }
    }
}
?>
  • 写回答

1条回答 默认 最新

  • doushuzd3033 2016-06-05 22:19
    关注

    As you stated: Normally you would create an array then fill it with all the items found in the database (or whatever source you're going to fetch it from).

    Side note: Instructing the MySQLi extension to fetch both associative and numeric is a bit time-wasting (and consuming, because the processor has to spend cycles on both).

    It would look something like this:

    $array = [];
    while ($row = $result->fetch_object()) { // fetch as object, nicer ;)
        $array[$result->title] = $result->price;
    }
    

    The array would now look something like:

    $array = [
        'Jungle book' => 26.95,
        'Mowgli' => 24.75,
        'Fantastic Four - E.12-6' => 100
    ];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀