PHP 添加到在 foreach 中创建的现有数组

我正在从数据库中选择值并将它们添加到循环中的数组中foreach,这是有效的。


之后,我在第二个查询中选择其他值,我想将这些值添加到同一个数组中,如何实现这一点?


请注意,我还不担心代码的安全性。


我的(简化的)代码如下;


$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();

这会产生;


[

  {

    "id": "981",

    "name": "jo",

    "username": "jo123",

    "email": "jo@example.com"

  },

  {

    "wb_status": "Complete"

  }

]

我需要这种格式;


[

  {

    "id": "981",

    "name": "jo",

    "username": "jo123",

    "email": "jo@example.com",

    "wb_status": "Complete"

  }

]


www说
浏览 143回答 1
1回答

海绵宝宝撒

在第一个查询之前运行第二个查询并将元素添加到数组中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();更新:另一种方法是迭代$users_arr并向每个元素插入所需的数据:// ...$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();
打开App,查看更多内容
随时随地看视频慕课网APP