2014-02-19 58 views
1

你好,我已经解码了一个json字符串,我发送到我的服务器,我试图从他的价值。访问数组值为空

我的问题是,我不能从内部数组获取值。

这是我的代码:

<?php 

    $post = file_get_contents('php://input'); 

    $arrayBig = json_decode($post, true); 

    foreach ($arrayBig as $array) 
    { 


    $exercise = $array['exercise']; 

    $response["exercise"] = $exercise; 
    $response["array"] = $array; 

    echo json_encode($response); 


    } 

?> 

当我从我的$response的答案,我得到这个值:

{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]} 

为什么$array['exercise']空,如果我可以看到,是不是空的array

谢谢。

+1

您应该执行'var_dump($ arrayBig)'。你可能会看到你的数组中有另一个数组。 – jeroen

+0

我建议你启用'display_errors'并将'error_reporting'设置为'E_ALL'。你有一个未定义的索引错误'$ array ['exercise']' – Phil

回答

2

通过观察的$response['array']的结果,它看起来像$array实际上是这个

[['exercise' => 'foo', 'reps' => 'foo']] 

即,嵌套在数字之一内的关联数组。您应该在盲目分配值之前做一些值检查,但为了简洁起见...

$exercise = $array[0]['exercise']; 
+0

感谢它的工作:) – dasdasd

2

由于[{...}],当您解码array密钥时,您将获得数组中的数组。

所以:

$exercise = $array['exercise']; 

应该是:

$exercise = $array[0]['exercise']; 

example here