PHP-将多个Json字符串转换为单个数组

时间:2016-06-15 06:27:45

标签: php arrays json

我有一个看起来像这样的结果集:

enter image description here

对于每个条目,可以有多个类别,我尝试解码这些JSON字符串并将其保存在单个数组中。这意味着,所有这些类别都将被解码并保存在一个数组中。该数据来自数据库。

这是我尝试过的代码:

//$resultset contains the entire resultset
$resultset_JSON='[["first","second","third","fourth"],["fifth","sixth","seventh","eight","ninth"]‌​,["life","death","business" ,"editing","light"]]';

$data= array();
while($row=mysqli_fetch_array($resultset))
{
    $data       =   json_decode($row['category']); 
    //$data[]   =   json_decode($row['category']);                      
}
print_r($data);

但我没有得到理想的结果。我只能获取最后一行。

任何人都可以帮我解决这个问题吗?

这是我试图获得的输出:

Array 
( 
  [0] => first
  [1] => second
  [2] => third
  [3] => fourth
  [4] => fifth
  [5] => sixth
  [6] => seventh
  [7] => eighth
  [8] => ninth
  [9] => life 
  [10] => death 
  [11] => business 
  [12] => editing 
  [13] => light 
) 

4 个答案:

答案 0 :(得分:1)

您可以在循环中使用array_merge

http://php.net/manual/fr/function.array-merge.php

答案 1 :(得分:1)

试试这个

$final_array = array();

while($row=mysqli_fetch_array($resultset))
{

  $temp_data       =   json_decode($row['category'],true); 
  $final_array     =   array_merge($final_array ,$temp_data);  

 }

 print_r($final_array );

答案 2 :(得分:1)

Please try this code:

$data= array();
$ds= array();
$f ='';
while($row=mysqli_fetch_array($resultset)){
{
    $data      =   json_decode($row['category']);   
    $f .= implode(',',$data);                       
}
if(!empty($f)) {
  $ds = explode(',',$f);
}
print_r($ds);

答案 3 :(得分:0)

  $resultset_JSON='[["first","second","third","fourth"],["fifth","sixth","seventh","eight","ninth"]‌​,["life","death","business" ,"editing","light"]]';

  $all_data = array();
  while($row=mysqli_fetch_array($resultset)){
      //Fetch array
      $data       =   json_decode($row['category']); 
      $all_data   =   array_merge($all_data,$data);                      
  }
  var_dump($all_data);