我收到以下错误:
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 43
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 44
当我试图解析以下json数据时:
"data":[
"phone":[
{"value":"",
"primary":true
}],
"email":[
{"value":"",
"primary":true
}]
]
以下陈述
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
//create array of the json data we want to export to csv
for ($x=0; $x<$count; $x++)
{
$jsonDataInArray[] = array
(
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
)
}
上述两个语句的语法有什么问题?我想知道我的语法上面是否有任何错误,特别是"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
答案 0 :(得分:1)
看起来您的JSON数据缺失{}
(格式不正确),而且,您在数字键阵列(phone
)上使用[]
键(按字母顺序排列)。要使用字母键,您必须有一个字典({}
,键值数组)。看起来你的JSON应该是这样的:
{
"data" :
[
{
"phone" :
{
"value" : "",
"primary" : true
},
"email" :
{
"value" : "",
"primary" : true
}
}
]
}
还要记住,计算数组中项目的函数是count()
,而不是Count()
(大写问题)。
我会这样做:
$jsonDataInArray = array();
$response = json_decode( $json_response, TRUE );
$data = $response['data'];
$count = count( $data );
foreach ( $data AS $index => $object )
{
$values = array(
"phone" => $data[$index]['phone']['value'],
"email" => $data[$index]['email']['value']
);
array_push( $jsonDataInArray, $values );
}
答案 1 :(得分:0)
这里的语法对我有用:
"phone" => $response['data'][$x]['phone'][0]['value'],
"email" => $response['data'][$x]['email'][0]['value']
json数据中的结束对象看起来像(警告:不是整个json数据字符串,只是结尾):
"phone":[{"value":"","primary":true}],"email":[{"value":"","primary":true}]
由于有数组,我必须包含[0]
以下代码:
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value']
可以使用这些结束json数据对象(警告:不是整个json数据字符串,只是结束):
"phone":{"value":"","primary":true},"email":{"value":"","primary":true}
答案 2 :(得分:-1)
循环中的语法错误。变化:
"email" => $response['data'][$x]['email']['value'],
致:
$email = $response['data'][$x]['email']['value'];