为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
www说 2023-06-24 18:13:27
我正在从数据库中选择值并将它们添加到循环中的数组中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"  }]
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

在第一个查询之前运行第二个查询并将元素添加到数组中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();


查看完整回答
反对 回复 2023-06-24
  • 1 回答
  • 0 关注
  • 142 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信