使用for循环在PHP中创建JSON对象

时间:2016-10-10 07:44:27

标签: php json rest

我正在尝试创建一个这样的JSON对象:

"results": [
{"key":"1","trackname":"graham@insideoutrenovations.com.au"},
{"key":"1","trackname":"sjwindsor@westnet.com.au"},
]

但是我的PHP代码为每次迭代创建一个新对象,json看起来像这样:

0: "{"key":"1","trackname":"graham@insideoutrenovations.com.au"}"
1: "{"key":"1","trackname":"sjwindsor@westnet.com.au"}"

这是我的php:

$results = array();

function json_response($trackName) {
return json_encode(array(
    'key' => '1',
    'trackname' => $trackName
));
}

//There is 3 reg expressions for each primary array so we need to iterate by 3, otherwise we will get 3 lots of the same email address
for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
    $results[] = json_response($matches[0][$i]);
}
//$results = call_user_func_array('array_merge',$results);
echo json_encode($results);

2 个答案:

答案 0 :(得分:2)

你需要删除第一个json_encode函数

您可以尝试创建关联数组或使用函数compact,这将为您完成工作。

//There is 3 reg expressions for each primary array so we need to iterate by   3, otherwise we will get 3 lots of the same email address
  for ($i = 0; $i < $numMatches; $i = $i + $patternNum) {
    $results[] = $matches[0][$i]; // json_encode removed
}

echo json_encode(array('results' => $results));
// or
echo json_encode(compact('results'));

答案 1 :(得分:1)

在最后echo中,您在json中编码已编码的数组。

json_encode功能中删除json_response