2017-01-24 32 views
0

我有一個多維數組這樣PHP:插入MySQL數據庫多維數組,只有特定的值

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()但我不知道具體如何。

+0

這是否http://stackoverflow.com/questions/25726512/how-to-insert-dynamic-multidimensional-array-in-database-with-mysqli幫你嗎? – SuperDJ

+0

是的,雖然我最初的問題不是如何將列插入數據庫,但我將如何從數組中獲得特定的值。比如我上面寫的「100,101」和「value4,value7」。 – arek

回答

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 
} 

?> 
+0

這工作正常!但我的問題是,ii顯示value4 value7在不同的行,而不是value4,value7 – arek

+0

推動這些值在數組然後implode它...然後它會給你的value4,value7 – pAsh

+0

完美!並與一個櫃檯,如果在第二foreach內,我做到了!非常感謝你 – arek

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); 



     } 

    ?>