首页 > 解决方案 > 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
        )
)

标签: phpmysqlarraysassociative-array

解决方案


@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


推荐阅读