I deduce value from mysqld json , through php . But the problem is that json is not quite valid.

The problem is that there is no comma between the brackets.

It turns out json this type:

 { { "id": "1", "tag_name": "span", } { "id": "2", "tag_name": "div" } } 

And you need this:

 { { "id": "1", "tag_name": "span", }, { "id": "2", "tag_name": "div" } } 

Here is an example of my code:

 $json_data = array('id' => $row['id'], 'tag_name' => $row['tag_name']); json_encode($json_data); 

How to make valid json ?

  • Collect an array of arrays, and not output each separately - andreymal

2 answers 2

If $row in your case is a foreach brute force element

Type:

 foreach($rows as $row) {...} 

First you need to collect the array you need, with an array of elements inside (Array of arrays).

Before the loop, declare an array:

 $newArray = array(); 

In a loop, do something like this:

 $newArray[] = array('id' => $row['id'], 'tag_name' => $row['tag_name']); 

After the cycle get json

 echo json_encode($newArray); 

    There is no need to specifically collect anything into an array, all modern APIs have functions that return a set of strings entirely

     $stmt = $pdo->query("SELECT id, tag_name FROM table"); echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC)); 

    or

     $res = $mysqli->query("SELECT id, tag_name FROM table"); echo json_encode($res->fetch_all(MYSQLI_ASSOC));