php - 遍历 while 数组并向项目添加更多属性 - PHP

标签 php mysql arrays mysqli

我在 PHP 中运行查询,遍历项目并将它们添加到数组中;

$select_all_restaurants = mysqli_query($connection, $query);
$rows = $select_all_restaurants -> num_rows;

$arr = array();
if($rows > 0) {
    while($rows = mysqli_fetch_assoc($select_all_restaurants)) { 
        $arr[] = $rows;
    }
}

如何从另一个查询中为数组中的每个项目将数据附加到 $arr 中。 因此,如果 item1 具有来自第一个查询的属性 id,name,当我运行第二个查询时,我想向它添加更多属性,例如 distance。所以在 $arritem1 中以 id,name,distance

结尾

我正在获取另一组数据的查询如下;

$info = get_driving_information($address1, $address2);
echo $info['distance'];
echo $info['time'];

另外,我从原始查询中获取了 $address1

这是我试过的;

$select_all_restaurants = mysqli_query($connection, $query);
$rows = $select_all_restaurants -> num_rows;

$arr = array();
if($rows > 0) {
    while($rows = mysqli_fetch_assoc($select_all_restaurants)) {

$info = get_driving_information($rows['address1'], $address2);
// I get two properties from this query
$info['distance'];
$info['time'];

// How do I add these 2 properties for every item in $arr?
//
        $arr[] = $rows;
    }
}

请指教

最佳答案

您只需将值附加到您的 $rows 对象即可

$arr = array();
if($rows > 0) {
    while($rows = mysqli_fetch_assoc($select_all_restaurants)) {
        $info = get_driving_information($rows['address1'], $address2);
        // I get two properties from this query
        $rows['distance'] = $info['distance'];
        $rows['time'] =  $info['time'];
        $arr[] = $rows;
    }
}

关于php - 遍历 while 数组并向项目添加更多属性 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629315/

相关文章:

python - 同时并行读取 numpy 数组

java - 在 JAVA 中用零初始化一个二维数组

php - 在 php 中获取给定月份和年份的开始和结束 unix 时间戳

php - 使用 Laravel Blade 显示来自 Postgres 的 JSON 数据

php - 禁用 woocommerce api 身份验证?

java.sql.SQLException : Incorrect string value: '\xAC\xED\x00\x05sr...' 异常

php - jquery 动态添加行有问题

mysql - 获取前 5 条记录及其每月计数

php - javascript 数组弹出

php - SQL - SET 和 IGNORE 在一条语句中