如何解决使用for或foreach循环创建具有关联数组的wordpress更新查询
我想通过循环创建一个关联数组,以将其添加到更新中。我遇到的问题是,我不知道如何遍历2个数组的每个元素来创建关联数组以放入更新查询中。
您可以在这里看到我在更新查询中将数组放入另一个数组中,但是它是错误的。
我以以下示例为例:
$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));
解决方法
您可以像这样从handleSelectTask
和$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];
您可以在此处看到输出(当然使用虚拟数据):https://sandbox.onlinephpfunctions.com/code/68c5f0a92b33625c437e4c5b9ef17c6f9b2ec4bb
或者,当您使用Array
(
[eleicons] => icons data
[elepro] => pro data
[elefont] => font data
[eleanimations] => animations data
)
时,可以这样创建数组:
$_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));
和table
,因此,如果将其添加到数据库中,则应先清除用户提供的所有数据,然后再将其添加到数据库中,否则您的数据库就很宽可以进行SQL注入。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。