PHP:在mysql数据库中插入多维数组,只有特定值

时间:2017-01-24 10:00:48

标签: php mysql arrays multidimensional-array

我有像这样的多维数组

Array =>
    [0] => Array
            (
                [address] => Zaa 6
                [category_ids] => Array
                    (
                        [0] => 100
                        [1] => 101
                    )

                [category_labels] => Array
                    (
                        [0] => Array
                            (
                                [0] => value1
                                [1] => value2
                                [2] => value3
                                [3] => value4
                         )

                        [1] => Array
                            (
                                [0] => value5
                                [1] => value6
                                [2] => value7
                            )

                    )

                [city] => gg
                [lat] => 37.964652
                [lng] => 23.708208
                [name] => New Place

            [1]=> Array the same as above

每个数组都是一个记录。

我想将所有元素放在mysql数据库中。但在列category_ids中,我想插入" 100,101"在category_labels中,我想只放置每个数组的最后一个值,例如" value4,value7"。我怎样才能做到这一点? 我知道我可以使用end()count()implode(),但我不知道具体如何。

2 个答案:

答案 0 :(得分:0)

<?php
$data=array(array(
                "address" => "Zaa",
                "category_ids" => array(100,101),

                "category_labels" => array(array("value1","value2","value3","value4"),array("value5","value6","value7")),
                "city" => "gg",
                "lat" => "37.964652",
                "lng" => "23.708208",
                "name" => "New Place"));


foreach($data as $row)
{
    echo $row['address']."<br>";

    $ids=implode(",",$row['category_ids']);

    echo $ids."<br>";

    $l_array=array();
    foreach($row["category_labels"] as $cat_label)
    {
       $count_l=count($cat_label);
        array_push($l_array,$cat_label[$count_l -1]);
    }
    echo implode(",",$l_array)."<br>";

    echo $row['city']."<br>";
    echo $row['lat']."<br>";
    echo $row['lng']."<br>";
    echo $row['name']."<br>";

    //write your query here by passing above parameters
}

?>

答案 1 :(得分:0)

我认为这正是你所需要的。循环遍历数组并像这样使用implode() end()

    <?php



        foreach($your_array as $key=>$val)
        {
           $ids ='';
           $new_cat_label='';

          $ids = implode(",",$val['category_ids']);


           foreach($val['category_labels'] as $val1)
           {
                if(!empty($new_cat_label))
                {

                    $new_cat_label.= " ,".end($val1);

                }
                else
                {

                   $new_cat_label.= end($val1);
                }

           }


          echo $ids."  <br>";
          echo $new_cat_label."  <br>";

           //here insert query 

          // insert into table_name (col1,col2)values($ids,$new_cat_label);



        }

    ?>