欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php數(shù)組轉(zhuǎn)換js數(shù)組操作及json_encode的用法詳解

 更新時間:2013年10月26日 09:55:24   作者:  
php數(shù)組轉(zhuǎn)換js數(shù)組操作及json_encode的用法。需要的朋友可以過來參考下,希望對大家有所幫助

對于php,個人感覺能夠熟練操作數(shù)組和字符串,基本上已經(jīng)是入門了,php本身有很多操作數(shù)組和字符串的函數(shù),今天在做一個功能時,需要用Js動態(tài)的創(chuàng)建門店信息,這些信息是要從后臺添加的,想來想去,通過php讀取數(shù)據(jù)庫,得到數(shù)組,然后將數(shù)組轉(zhuǎn)化成符合需求js數(shù)組,
php數(shù)組形式為:

復(fù)制代碼 代碼如下:

$newArray = array(array('地區(qū)'=>'北京地區(qū)','items'=>'10','detail'=>array(0=>array('店名'=>'旗艦店','url'=>'http://www.'),1=>array('店名'=>'jjjj','url'=>'http://www.fdd'))),
                  array('地區(qū)'=>'上海地區(qū)','items'=>'11','detail'=>array(0=>array('店名'=>'旗艦店','url'=>'http://www.'),1=>array('店名'=>'jjjj','url'=>'http://www.fdd'))),
                 );

這里用的一個很方便的函數(shù):json_encode();
var jsarray = new Array();
jsarray = <?php echo json_encode($newwarr);?>;
用console.log();可以看到j(luò)sarray的結(jié)構(gòu)。   

在這里如何構(gòu)造這樣一個符合要求的php數(shù)組呢?(我用的是phpcms系統(tǒng))

復(fù)制代碼 代碼如下:

    $sql= 'select catid,catname,items from category where parentid=10';
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
     $arrArea['地區(qū)'] = $row['catname'];
     $arrArea['items'] = $row['items'];
     unset($arrArea['detail']);//這一步很關(guān)鍵,要不得出的信息就會累加。
     $sql2 = 'select title,url from news where catid='.$row['catid'];
     $fendian = mysql_query($sql2);
     while ($re=mysql_fetch_assoc($fendian)) {
      $item['店名']=$re['title'];
      $item['url']=$re['url'];  
      $arrArea['detail'][] = $item; 
     }
     $newwarr[]=$arrArea;
    }   
    var_dump($newwarr);

json_encode:對變量進行 JSON 編碼,該函數(shù)只能接受 UTF-8編碼的數(shù)據(jù) .

相對應(yīng)的還有json_decode,第二個參數(shù)為true,返回數(shù)組,執(zhí)行相逆的過程。

json只能用對象和數(shù)組。

相關(guān)文章

最新評論