我正在尝试使用unset从数组中删除Product
元素,但是它不起作用。另外,需要使用MySql插入此数组。我该如何实现?
unset( $ar2['Product'] );
print_r($ar2);
结果显示为Product
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
答案 0 :(得分:0)
您的代码应为
foreach ($ar2 as $array) {
unset( $array['Product'] );
}
因为您需要从第一个数组的每个元素中取消设置键product
。
要插入它,您可以在同一循环内使用插入查询。
foreach ($ar2 as $array) {
unset( $array['Product'] );
$sql = "insert into table_name column1,column2 values ($array['Price'],$array['Img'];";
}
我假设您知道如何将值插入MySql。
否则,请使用以下教程。
https://www.w3schools.com/php/php_mysql_insert.asp
修改
在循环中使用此代码可删除多个键。
$keys = array('key1', 'key2');///all the keys you need to remove
foreach($keys as $key) {
unset($arr[$key]);
}
答案 1 :(得分:0)
@kane 代码中的错误是您没有访问正确的数组索引。
Array
(
[0] => Array
(
[Product] => Resume, CV, vCard & Portfolio HTML5 Template
[Price] => 10
[Img] => http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg
)
[1] => Array
(
[Product] => Runhill – Multipurpose Construction WP Theme
[Price] => 39
)
)
在您的数组中,产品索引出现在数字索引之后,即 您可以使用Yasii的方法,也可以尝试array_map遍历数组数组并取消设置产品密钥。
<?php
$data=array(
array(
'Product' => 'Resume, CV, vCard & Portfolio HTML5 Template',
'Price' => 10,
'Img' => 'http://localhost/envy-theme-new/wp-content/uploads/2019/01/cv.jpg'
),
array(
'Product' => 'Runhill – Multipurpose Construction WP Theme',
'Price' => 39
)
);
$data = array_map(function($arr){
unset($arr['Product']);
return $arr;
}, $data);
echo '<pre>';
var_dump($data);
对于将PHP数组插入Mysql数据库,您需要根据数组值创建一个insert语句,并且必须处理丢失的索引值(例如“ Img”键值缺少第二个子数组数组)
在使用数组之前,请先了解在php中使用数组的最佳方法: https://code.tutsplus.com/tutorials/working-with-php-arrays-in-the-right-way--cms-28606
PHP7不再支持使用mysql ext将数据插入数据库。 请改为使用PDO。
在这里回答类似的查询: Insert array into MySQL database with PHP
PDO教程: https://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059