简体   繁体   中英

Loop through while array and add more properties to items - PHP

I'm running a query in PHP, looping through the items and adding them to an array;

$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;
    }
}

How can I append data into $arr from another query and for each of the items in the array. So if item1 has properties id,name from the first query, when I run the second query I want to add more properties to it eg distance . So in $arr item1 ends up with id,name,distance

The query I'm getting the other set of data is below;

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

Also I'm getting $address1 from the original query.

This is what I've tried;

$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;
    }
}

Please advise

You can just append the values to your $rows object like

$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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM