鍍金池/ 問答/PHP  HTML/ jq數(shù)組跟字符串轉換

jq數(shù)組跟字符串轉換

function encode($array)
{
        if(version_compare(PHP_VERSION,'5.4.0','<')){
        $str = json_encode($array);
        $str = preg_replace_callback("#\\\u([0-9a-f]{4})#i",function($matchs){
           return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
        },$str);
        return $str;
        }else{
        return json_encode($array, JSON_UNESCAPED_UNICODE);
        }
}

這是轉換中文的函數(shù);
clipboard.png
我從數(shù)據(jù)庫中查出數(shù)據(jù)然后轉為json格式,
這是html中js;

 function test(){
        var id = $(".father option:selected").val();
        $.ajax({
            url: 'regulation_type.php',
            type: 'post',
            data: {id:id , act:'ajax'},
            success:function(msg){
                //var str = '{"id":"2","title":"刑法的任務","parent_id":"1","chapter":"第一章"}';
                //obj = JSON.parse(str);
                console.log(msg);
                str = msg.replace('[{','{');
                str_1 = msg.replace('}]','}');
                console.log(str_1);

直接輸出msg,得到[{"id":"2","title":"刑法的任務","parent_id":"1","chapter":"第一章"}],外面套了個[],我以為是數(shù)組,用typeof看了下是字符串,obj = JSON.parse(json);輸出obj.id沒有值,然后單獨寫了{"id":"2","title":"刑法的任務","parent_id":"1","chapter":"第一章"};用obj = JSON.parse(json);輸出obj.id有值,然后就想著把外面的[]去掉,可是怎么去都去不掉,str = msg.replace('[{','{');str_1 = msg.replace('}]','}');右邊的可以去掉,可是左邊的一直去不掉,有沒有哪個大神知道原因的,求解,在線等!

回答
編輯回答
苦妄

因為你獲取數(shù)據(jù)是用的是getAll(),獲取了多條數(shù)據(jù),所以obj是個2維數(shù)組,所以要用循環(huán)

obj = JSON.parse(str);
for(var o in obj)
{
    console.log(obj[o].id);
}

如果你只想要第一條數(shù)據(jù):
方法1:
不要使用getAll()方法
方法2:

echo encode($res[0]);

方法3:

obj = JSON.parse(str);
obj = obj[0];
console.log(obj.id);

方法1最好

2017年6月23日 20:54
編輯回答
心癌

那你當數(shù)組取不就好了 返回的數(shù)組 以后返回多項刪除[]就不能正確parse了啊

2018年7月22日 13:26