simple get json_decode数组值,错误不明白

时间:2017-02-18 11:35:17

标签: php

<?php

$playerBox = json_decode($_POST['player_data'], true);

echo print_r($playerBox);

echo $playerBox['name'];

?>

我正在通过ajax向php发送一个数组,这是我的php代码,我的目的是获取每个值并为其创建一个html p。

但是我无法获得每个值,我不知道为什么每个人都可以使用它来获取它。

这是print_r上的$ _POST [&#39; player_data&#39;)

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Jonny
            [number] => 27
        )

    [1] => Array
        (
            [id] => 2
            [name] => dx
            [number] => 28
        )

)  

我得到的错误

<br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined index: name in C:\wamp\www\objecttest\directory\class-mail.php on line <i>7</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0004</td><td bgcolor='#eeeeec' align='right'>135312</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp\www\objecttest\directory\class-mail.php' bgcolor='#eeeeec'>..\class-mail.php<b>:</b>0</td></tr>
</table></font>

我如何获得每个值并像这样创建?

id   name    number

1   Johnny     27

2   dx         28  

2 个答案:

答案 0 :(得分:0)

你必须使用像这样的索引号访问你的数组

 $playerBox[0]['id'];
$playerBox[0]['name'];
$playerBox[0]['number'];

答案 1 :(得分:0)

只需对数组使用foreach迭代并获取每个索引值

   <table border="1px" >
      <thead>
        <tr>
         <th>ID</th>
         <th>Name</th>
         <th>Number</th>
       </tr>
     </thead>
     <tbody>
<?php

  foreach($playerBox as $play)
  {
   ?>
    <tr>
       <td><?php echo $play['id']; ?> </td>
       <td><?php echo $play['name']; ?></td>
       <td><?php echo $play['number']; ?></td>
    </tr>
  <?php
  }
 ?>
 </tbody>
 </table>
相关问题