用于json回复的php变量

时间:2016-09-01 09:24:56

标签: php arrays json

这是我的回复

Array ([code] => 202 [message] => Accepted [data] => Array ( [resultMap] => Array ( [D3856~H158] => Array ( [AppDay] => * [HosTown] => Colombo 06 [SpecName] => Physiotherapist/Sports Physiotherapist [HosName] => Revival Healthcare Services (Pvt)-Colombo [SpecializationId] => 333 [HosCode] => H158 [AppDate] => Any [DocName] => MR CHAMARA MATHANGAWEERA [DoctorNo] => D3856 ) ) ) [detailMessage] => Success ) 

现在我想为这个值分配变量并以正确的方式回声我尝试这个 但它给出了一个错误消息

未定义的索引:DocName

这是我的代码 ////////////////////////////////////

if( $response ){
    if ( isset($result->error) )die( $result->error_message );
    /* Convert json data to array */
    $arr=json_decode( $response, true );
    //print_r($arr);
    foreach($arr['data'] as $data)
    {
        $output="Doctor".$data['DocName']."<br/>";
        $output="Doctor".$data['SpecName']."<br/>";
        $output="Doctor".$data['HosName']."<br/>";
        $output="Doctor".$data['Day']."<br/>";
        $output="Doctor".$data['Date']."<br/>";
    }

2 个答案:

答案 0 :(得分:2)

查看数组的结构。您要查找的值嵌套了几个数组:

$data = array (
    'code' => 202,
    'message' => 'Accepted', 
    'data' => array ( 
        'resultMap' => array ( 
            'D3856~H158' => array ( 
                'AppDay' => '*', 
                'HosTown' => 'Colombo 06',
                'SpecName' => 'Physiotherapist/Sports Physiotherapist',
                'HosName' => 'Revival Healthcare Services (Pvt)-Colombo',
                'SpecializationId' => 333,
                'HosCode' => 'H158',
                'AppDate' => 'Any',
                'DocName' => 'MR CHAMARA MATHANGAWEERA',
                'DoctorNo' => 'D3856',
            ) 
        ) 
    ),
    'detailMessage' => 'Success'
);

打印resultMap中第一条记录的所有值:

foreach(current($data['data']['resultMap']) as $key => $value) {
    echo $key . " => " . $value . "<br />";
}

您需要一个额外的循环才能在resultMap中打印所有记录。

答案 1 :(得分:0)

你可以试试这个工作正常  对于这个固定的数组值意味着给定

foreach($arr['data']['resultMap']['D3856~H158'] as $data)
 {
        $output="Doctor".$data['DocName']."<br/>";
        $output="Doctor".$data['SpecName']."<br/>";
        $output="Doctor".$data['HosName']."<br/>";
        $output="Doctor".$data['Day']."<br/>";
        $output="Doctor".$data['Date']."<br/>";


 } 

更改的数组值给出了答案

foreach($arr['data']['resultMap'] as $data)
 {
        $output="Doctor".$data['DocName']."<br/>";
        $output="Doctor".$data['SpecName']."<br/>";
        $output="Doctor".$data['HosName']."<br/>";
        $output="Doctor".$data['Day']."<br/>";
        $output="Doctor".$data['Date']."<br/>";


 }