search

Home  >  Q&A  >  body text

php - How to process this array to ensure that the inserted data is accurately stored in the database? ?

There is an array structure like this:

array (size=3)
  19 =>
    array (size=4)
      'pro_id' => string '44' (length=2)
      'attr_id' => int 19
      'attr_value' =>
        array (size=1)
          0 => string '12 months' (length=8)
      'attr_price' =>
        array (size=1)
          0 => string '200' (length=3)
  20 =>
    array (size=4)
      'pro_id' => string '44' (length=2)
      'attr_id' => int 20
      'attr_value' =>
        array (size=1)
          0 => string 'Calculated based on 5%' (length=14)
      'attr_price' => null
  18 =>
    array (size=4)
      'pro_id' => string '44' (length=2)
      'attr_id' => int 18
      'attr_value' =>
        array (size=2)
          0 => string 'Declaration without invoice 0' (length=16)
          1 => string 'Declaration based on invoice amount' (length=18)
      'attr_price' =>
        array (size=2)
          0 => string '100' (length=3)
          1 => string '200' (length=3)
          

The data table structure is as follows:

< /p>

The result I want is as above, how should I deal with it? ? Data table structure

DROP TABLE IF EXISTS `dhd_product_attr`;
CREATE TABLE `dhd_product_attr` (
  `pro_attr_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pro_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
  `attr_id` smallint(5) unsigned NOT NULL DEFAULT '0',
  `attr_value` text NOT NULL,
  `attr_price` varchar(255) NOT NULL COMMENT 'This attribute corresponds to the price to be added to the original price of the product',
  PRIMARY KEY (`pro_attr_id`),
  KEY `pro_id` (`pro_id`),
  KEY `attr_id` (`attr_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

How to deal with this array? ?

巴扎黑巴扎黑2800 days ago467

reply all(4)I'll reply

  • PHPz

    PHPz2017-05-16 13:12:51

    $array = ['你的数组'];
    $insert = [];
    
    foreach($array as $val){
        foreach($val['attr_value'] as $key=>$attr_val){
             $insert[]=[
                'pro_id'=>$val['pro_id'],
                'attr_id'=>$val['attr_id'],
                'attr_value'=>$attr_val,
                'attr_price'=>$val['attr_price'][$key],
             ]
        }
    }
    
    //你这第一个个字段没看出来怎么确定 加到$insert 这个数组里就行

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-16 13:12:51

    foreach reorganizes the array and changes it to the format corresponding to the database

    reply
    0
  • 世界只因有你

    世界只因有你2017-05-16 13:12:51

    I just don’t know how to reorganize this code

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-16 13:12:51

    Simple and crude, two layers of foreach or use one layer of foreach and list function

    reply
    0
  • Cancelreply