php array conversion js array operation and json_encode usage details

  • 2020-10-31 21:39:37
  • OfStack

For php, personal felt able to skillfully operate arrays and strings, basically is the introduction, php itself has a lot of operation and the function of the string array, when doing a function today, need to use Js dynamically create stores information, this information is to add from the background, want to want to go, by php read database, array, then arrays into js meet demand,
The php array is as follows:


$newArray = array(array(' region '=>' In the Beijing area ','items'=>'10','detail'=>array(0=>array(' The name '=>' Flagship store ','url'=>'http://www.'),1=>array(' The name '=>'jjjj','url'=>'http://www.fdd'))),
                  array(' region '=>' In the Shanghai area ','items'=>'11','detail'=>array(0=>array(' The name '=>' Flagship store ','url'=>'http://www.'),1=>array(' The name '=>'jjjj','url'=>'http://www.fdd'))),
                 );

One handy function to use here is json_encode();
var jsarray = new Array();
jsarray = < ?php echo json_encode($newwarr);? > ;
Use console. log (); You can see the structure of jsarray.

How do you construct an php array that meets this requirement here? (I use the phpcms system)


    $sql= 'select catid,catname,items from category where parentid=10';
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
     $arrArea[' region '] = $row['catname'];
     $arrArea['items'] = $row['items'];
     unset($arrArea['detail']);// this 1 Step is critical, otherwise the resulting information will add up. 
     $sql2 = 'select title,url from news where catid='.$row['catid'];
     $fendian = mysql_query($sql2);
     while ($re=mysql_fetch_assoc($fendian)) {
      $item[' The name ']=$re['title']; 
      $item['url']=$re['url'];   
      $arrArea['detail'][] = $item; 
     }
     $newwarr[]=$arrArea;
    }    
    var_dump($newwarr);

json_encode: Encodes the variable JSON, and this function can only accept es35EN-8 encoded data.

Correspondingly, json_decode, the second parameter is true, returns an array, and performs the inverse procedure.

json can only use objects and arrays.


Related articles: