第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

PHP 添加到在 foreach 中創(chuàng)建的現(xiàn)有數(shù)組

PHP 添加到在 foreach 中創(chuàng)建的現(xiàn)有數(shù)組

PHP
www說 2023-06-24 18:13:27
我正在從數(shù)據(jù)庫(kù)中選擇值并將它們添加到循環(huán)中的數(shù)組中foreach,這是有效的。之后,我在第二個(gè)查詢中選擇其他值,我想將這些值添加到同一個(gè)數(shù)組中,如何實(shí)現(xiàn)這一點(diǎn)?請(qǐng)注意,我還不擔(dān)心代碼的安全性。我的(簡(jiǎn)化的)代碼如下;$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();這會(huì)產(chǎn)生;[  {    "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貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊

在第一個(gè)查詢之前運(yùn)行第二個(gè)查詢并將元素添加到數(shù)組中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并向每個(gè)元素插入所需的數(shù)據(jù):


// ...

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


查看完整回答
反對(duì) 回復(fù) 2023-06-24
  • 1 回答
  • 0 關(guān)注
  • 196 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)