Skip to content
Advertisement

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

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>"
    ]
}

Advertisement

Answer

Okay I found a solution. Here is my answer:

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

            }
            header('Content-Type: application/json');
            $arr1 =  json_encode($testtt, JSON_UNESCAPED_SLASHES);
            echo $arr1;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement