亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 for 或 foreach 循環完成的關聯數組創建 WordPress 更新查詢

使用 for 或 foreach 循環完成的關聯數組創建 WordPress 更新查詢

PHP
呼如林 2023-10-21 20:00:44
我想通過循環創建一個關聯數組以將其添加到更新中。我遇到的問題是,我不知道如何遍歷兩個數組的每個元素來創建關聯數組以放入更新查詢中。您可以在這里看到我將數組放入更新查詢中的另一個數組中,但這是錯誤的。我有以下例子:$table = 'name';$data = [$_POST['eleicons'], $_POST['elepro'], $_POST['elefont'], $_POST['eleanimations']];$names = ['eleicons', 'elepro', 'elefont', 'eleanimations'];$counter = 0;update($table,array(foreach($name as $one => $dat){$one => $dat[$counter],$counter++;}),array('id' => 0));正如我所說,該數組是關聯的。更新函數應該如下所示:update($table,array($name[0] => $data[0],$name[1] => $data[1],$name[2] => $data[2],$name[3] => $data[3],),array('id' => 0));但我想這樣做:update($table,$array_associative,array('id' => 0));
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

$names您可以從您的和 中創建一個關聯數組,$data如下所示:


$count = sizeof($names);    // Get the number of elements in the arrays

// for each element, add the name as the key and the data as the value:

for($i=0; $i<$count; $i++)

    $associative_array[$names[$i]] = $data[$i];

這將創建一個像這樣的數組:


Array

(

    [eleicons] => icons data

    [elepro] => pro data

    [elefont] => font data

    [eleanimations] => animations data

)

您可以在這里看到輸出(當然使用虛擬數據):https ://sandbox.onlinephpfunctions.com/code/68c5f0a92b33625c437e4c5b9ef17c6f9b2ec4bb


或者,當您使用 時$_POST,您可以這樣創建數組:


foreach($names as $key)

    $associative_array[$key] = $_POST[$key];

整個代碼將是:


$table = 'name';

$names = array('eleicons', 'elepro', 'elefont', 'eleanimations');    

$associative_array = array();


foreach($names as $key)

    $associative_array[$key] = $_POST[$key];


update($table,

       $associative_array,

       array('id' => 0));

重要的提示:


您正在代碼中使用tableand ,因此如果您要將其添加到數據庫中,則應該在將其添加到數據庫之前清理所有用戶提供的數據,否則您很容易受到 SQL 注入的影響。update


查看完整回答
反對 回復 2023-10-21
  • 1 回答
  • 0 關注
  • 140 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號