John Davidson

html - Convert a series of PHP variables to a JSON object through a loop

0 comments
Message:


I have an array that I loop through because the array is unknown. I would like to output the result of the loop as Json but unfortunately I always get an error message: "SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 74 of the JSON data". Here is my code.:


$testtt = array();
foreach (array_combine($links, $domain) as $link => $name) {
$testtt['html'] = "<ul class='a'><li><a href=$link>$name</a></li></ul>";


header('Content-Type: application/json');
$arr = array_filter($testtt);
$arr1 = json_encode($arr, JSON_UNESCAPED_SLASHES);
echo $arr1;
}


It should come out normal JSON that it looks like this.


{
"html":[
"<ul class='a'><li><a href= https://www.code.de>Code</a></li></ul>",
"<ul class='a'><li><a href= https://www.stackoverflow.de>stack</a></li></ul>"
]
}


My Answer:
To achieve the desired JSON output, you need to store each iteration of the loop in an array and then encode the final array to JSON. Here is the updated code:

php
$testtt = array();
foreach (array_combine($links, $domain) as $link => $name) {
$testtt['html'][] = "";
}

header('Content-Type: application/json');
$arr = array_filter($testtt);
$arr1 = json_encode($arr, JSON_UNESCAPED_SLASHES);
echo $arr1;


This code will output the JSON object with the "html" key containing an array of HTML strings as shown in your example. Each iteration of the loop will add a new HTML string to the "html" array.

Rate this post

5 of 5 based on 6236 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us