在数组中循环并向项添加更多属性 - PHP

时间:2015-11-10 11:50:30

标签: 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。因此,在$arr中,item1以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;
    }
}

请告知

1 个答案:

答案 0 :(得分:0)

您可以将值附加到$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;
    }
}