0

I have never needed json previously, so I have almost zero experience...

I am outputting multiple arrays into a json file using the following code:

$file= 'myfile.json';

$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
    $newcont=json_encode($contents, JSON_PRETTY_PRINT);
    print_r($newcont);
    file_put_contents($file, $newcont);

This is working as expected, and the output gives me something similar to this:

"name": [
    "joe blogs",
    "random name 2",
    "random name 3",
    etc,
    etc
],
"busname": [

    "ABC business",
    "DEF business",
    "HIJ business",
    etc,
    etc
],
"busdesc": [
    "We do stuff",
    "We do other stuff",
    "We don't do anything",
    etc,
    etc
],

etc

Is it possible to (with a simple method) have the output to be more like:

"id1": [  "joe blogs", "ABC business", "We do stuff", etc ]
"id2":  [   "random name 2", "DEF business", "We do other stuff", etc ]
"id3":  [   "random name 3", "HIJ business", "We don't do anything", etc ]
etc

Layout is not particularly important, but getting them grouped together is.

I have had little success with getting relevant results from Google searches.

The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.

Many thanks


Edit:

I have undeleted this as my attempt at fixing did not work.

Here is the code:

$results = mysqli_query($con,"SELECT * FROM membersites  WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
    $r1 = $business['id'];
    $id[]=$r1;
    $r2 = $business['name'];
    $name[]=$r2;
    $r4 = $business['busname'];
    $busname[]=$r4;
    $r5 = $business['busdesc'];
    $busdesc[]=$r5; 

    $all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}

$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);

This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.

Again, please bare in mind that this is the first project that I have had to output any json files.

Any help will be appreciated :)


Edit 2 (for clarity)

Final output needs to look like this

{
    [
        {
            "id":"1",
            "name":"joe blogs",
            "busname":"ABC business",
            "busdesc":"We do stuff"
        },
        {
            "id":"2",
            "name":"joe blogs",
            "busname":"random name 2",
            "busdesc":"We do other stuff"
        },
        etc
    ]
}

This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.

Apologies for being awkward.

10
  • 1
    I'm sure you could do this at whatever point you put together $name, $busname, etc, etc. Commented Nov 27, 2018 at 2:06
  • The previous lines are reading the data from a database : eg: while($business = mysqli_fetch_array($results)) { $result = $business['name']; $name[]=$result; } I guess I could also create a new array at this point which has all these combined like you suggest - and just use this for the json creation? Commented Nov 27, 2018 at 2:10
  • That would be my suggestion. Generally such a structure would be more helpful than disparate lists of data anyway. Commented Nov 27, 2018 at 2:12
  • great idea... for some reason that never occurred to me. Thank you. If you like, you can repeat that as an answer and I'll accept it :) Commented Nov 27, 2018 at 2:15
  • 1
    No, the question is too broad and the answer too short to be of use to future visitors. I'd suggest just deleting it. Commented Nov 27, 2018 at 2:18

2 Answers 2

2

When you loop on your records from DB, build a multi-dimensional array:

while($business = mysqli_fetch_array($results))
{
    $all[] = [
        'id' => $business['id'],
        'name' => $business['name'],
        'busname' => $business['busname'],
        'busdesc' => $business['busdesc'],
    ];
    // or 
    $all[] = $business;
    // or 
    $all[ $business['id'] ] = $business;
}

Then you can encode your multidimensional array into JSON like this:

$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);

the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])

Sign up to request clarification or add additional context in comments.

Comments

2

I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:

$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);

You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.

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.