php - PHP删除元素表单数组无法正常工作
问题描述
我正在尝试Product
使用 unset 从数组中删除元素,但它不起作用。另外,需要使用 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
)
)
解决方案
@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 数据库,您需要从数组值创建一个插入语句,并且必须处理缺少的索引值,例如“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
推荐阅读
- r - 在多个列的循环中计算描述性统计信息
- java - 指定的安装文件夹是只读的 Netbeans 错误信息
- angular - Angular Shared Service - 将项目添加到列表时,共享服务正在复制数据
- arrays - 如何在 Swagger (PowerApps) 中捕获 JSON 数组值
- python - 使用 WTForms 填充 textarea 字段
- mobile - GWT 移动/触摸屏设备 - 启用玻璃的自动隐藏 PopupPanel 在点击玻璃时触发触摸/单击底层小部件
- typescript - 如何从 Firestore 读取地图
- install4j - Install4j 没有在 MacOS 的预构建 JRE 中保持链接
- graphql - 在 Blazor WebAssembly 中使用 GraphQL API
- r - 如何在 R 中的 if else 语句中忽略跨多个列的 NA?