0

I am trying to create a JSON object like this:

"results": [
{"key":"1","trackname":"[email protected]"},
{"key":"1","trackname":"[email protected]"},
]

However my PHP code is creating a new object for each iteration, the json looks like this:

0: "{"key":"1","trackname":"[email protected]"}"
1: "{"key":"1","trackname":"[email protected]"}"

Here is my 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);
1
  • what is your problem? Commented Oct 10, 2016 at 7:46

2 Answers 2

2

you need to remove the first json_encode function

you can either try to create associative array or use function compact, that will do the work for you.

//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'));
Sign up to request clarification or add additional context in comments.

Comments

1

In final echo you encode in json an array already encoded.

Remove json_encode from json_response function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.