如何在PHP中使用数组JSON?

时间:2017-01-24 03:33:16

标签: javascript php arrays json

我是一名JavaScript程序员,并且有一个PHP项目。 我在使用PHP工作JSON时遇到了麻烦。

这是我的JSON

{
   "orders":[
  {
     "name":"#1002"
  },
  {
     "name":"#1001"
  }
  ]
}

我需要获取每个名称并回显它们,我尝试了以下代码$myarray = json_decode($order, true),但它返回了我的错误。

警告:json_decode()期望参数1为字符串,数组在

中给出

如何将json从数组转换为字符串?或者我做错了。

2 个答案:

答案 0 :(得分:0)

只需将json响应保存在变量上即可。然后做json_decode

$orders = '{
       "orders":[
         {
            "name":"#1002"
         },
         {
            "name":"#1001"
         }
      ]
}';
$myarray = json_decode($orders, true);

现在执行print_r将产生类似

的结果
echo '<pre>';
print_r($myarray);

结果

Array
(
    [orders] => Array
        (
            [0] => Array
                (
                    [name] => #1002
                )

            [1] => Array
                (
                    [name] => #1001
                )

        )

)

编辑:

为了只获取名称值,只需运行foreach

$result = [];
foreach($myarray['orders'] as $value) {
    $result[] = $value['name'];
}

现在打印$ result你会得到

Array
(
    [0] => #1002
    [1] => #1001
)

答案 1 :(得分:0)

的config.php

<?php 
$con = mysql_connect('localhost','root','');
mysql_select_db('db_school',$con);
$sql = "SELECT * FROM userlogin";
$result = mysql_query($sql,$con);
$data = array();
while ($row = mysql_fetch_array($result)) {
    $data[] =array(
        'id'=>$row['id'],
        'username'=>$row['username'],
        'userpass'=>$row['userpass'],
    );
}
echo json_encode(array('data'=>$data));
 ?>

view.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="tbl" border="1">
        <thead><tr>
            <th>Id</th>
            <th>Username</th>
            <th>Password</th>
        </tr></thead>
        <tbody></tbody>
    </table>
    <script type="text/javascript">
        $.ajax({
            url: 'config.php',
        }).done(function(res) {
            var res_data = JSON.parse(res),table='';
            $.each(res_data.data,function(index, el) {
                console.log(el.id,' ', el.username,' ',el.userpass);
                table+='<tr>';                
                table+='<td>'+el.id+'</td>';                
                table+='<td>'+el.username+'</td>';                
                table+='<td>'+el.userpass+'</td>';                
                table+='</tr>';                
            });
            $('#tbl').html(table);
        });
    </script>

演示:

enter image description here