Search code examples
phparraysjsonforeacharray-push

PHP Adding to Existing Array Created in foreach


I am selecting values from a database and adding these to an array in a foreach loop, this works.

After this I am selecting additional values in a second query, I want to add these values to the same array, how can I achieve this?

Please note I am not concerned about the security of the code just yet.

My (simplified) code is below;

$users_arr = array();
// first query
$db->setQuery("SELECT id, name, username, email FROM sometable WHERE name = '$name' ");
$results = $db->loadObjectList();

foreach ($results as $result) {
    $userid = $result->id;
    $name = $result->name;
    $username = $result->username;
    $email= $result->email;
    $users_arr[] = array(
      "id" => $userid, 
      "name" => $name, 
      "username" => $username, 
      "email" => $email);
}

// second query
$db->setQuery("SELECT status AS wb_status FROM anothertable ");
$wb = $db->loadObject();

$wb_status = $wb->wb_status;

// add to original array 
$users_arr[] = array("wb_status" => $wb_status);

echo json_encode($users_arr);
exit();

This produces;

[
  {
    "id": "981",
    "name": "jo",
    "username": "jo123",
    "email": "[email protected]"
  },
  {
    "wb_status": "Complete"
  }
]

I need it in this format;

[
  {
    "id": "981",
    "name": "jo",
    "username": "jo123",
    "email": "[email protected]",
    "wb_status": "Complete"
  }
]

Solution

  • Run second query before first and add element to array in foreach:

    // second query becomes first
    $db->setQuery("SELECT status AS wb_status FROM anothertable ");
    $wb = $db->loadObject();
    
    $wb_status = $wb->wb_status;
    
    $users_arr = array();
    // first query becomes second
    $db->setQuery("SELECT id, name, username, email FROM sometable WHERE name = '$name' ");
    $results = $db->loadObjectList();    
    
    foreach ($results as $result) {
        $userid = $result->id;
        $name = $result->name;
        $username = $result->username;
        $email= $result->email;
        $users_arr[] = array(
          "id" => $userid, 
          "name" => $name, 
          "username" => $username, 
          "email" => $email
          "wb_status" => $wb_status, // Here
        );
    }
    
    echo json_encode($users_arr);
    exit();
    

    Update: another approach is to iterate over $users_arr and insert required data to each element:

    // ...
    $db->setQuery("SELECT status AS wb_status FROM anothertable ");
    $wb = $db->loadObject();
    
    $wb_status = $wb->wb_status;
    
    // I use `&` here so as to pass `$item` as a
    // reference to original item in `$users_arr`
    foreach ($users_arr as &$item) {
        $item["wb_status"] = $wb_status;
    }
    
    echo json_encode($users_arr);
    exit();