0

First off, sorry if the title is off...it's the best thing I could think of as to what issue I'm facing.

In my database, I have a list of apps. In PHP, I'm pulling their data from their key, and encoding that data into JSON to be printed out (I'm making an API).

However, only the last app gets printed out in JSON. What I need is a JSON array with ANY apps that have the same key so I can loop through them later, and print out their data.

My code:

$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);

if ($appData->num_rows > 0){ // Check if app_key exists
    while($row = $appData->fetch_assoc()) { // While retrieving rows
        $jsonApp = json_encode(array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        ), JSON_UNESCAPED_SLASHES);
    }
    // Format and print JSON data
    echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

For the above, I tried echoing the JSON data in the while loop, but that (as expected) printed <pre>s for every row.

Here's the JSON output from the above code:

{
    "app_name":"Andrew's Second App",
    "app_theme":{
        "primary_color":"#FFFFFF",
        "primary_color_dark":"#E0E0E0",
        "accent_color":"#E91E63"
    },
    "app_navigation":"0",
    "author_info":{
        "author_name":"Andrew Quebe",
        "author_bio":"I'm a developer of stuff.",
        "links":{
            "website":"http://www.andrewquebe.com",
            "googleplus":"https://plus.google.com/+AndrewQuebe",
            "twitter":"https://twitter.com/andrew_quebe",
            "dribble":"None",
            "behance":"None"
        }
    },
    "app_status":"1"
}

Note: the data is perfectly formatted, but I need the data to be in an array and I'm unsure as to how to do this.

4
  • That's a valid JSON string, what do you mean by I need the data to be in an array? Can you show us a sample expected output? Commented Jan 15, 2017 at 1:48
  • you overwrite $jsonApp on each loop, rather than adding to it Commented Jan 15, 2017 at 1:49
  • @RajdeepPaul yes...something like this: pastebin.com/ZBFkDyXy Commented Jan 15, 2017 at 2:13
  • 1
    @AndrewQuebe I've given an answer below, hopefully this will resolve your issue. Commented Jan 15, 2017 at 2:23

4 Answers 4

1

The problem is, you're applying json_encode() function in each iteration of while() loop, plus you're overwriting $jsonApp in each iteration. And that's why you're getting that output.

The solution is, create an empty result array outside of while() loop. In each iteration of while() loop, push that array into the result array. And finally after coming out of the loop, apply json_encode() function on the result array and display it.

So your code should be like this:

// your code

if ($appData->num_rows > 0){ // Check if app_key exists
    $resultArr = array();
    while($row = $appData->fetch_assoc()) { // While retrieving rows
        $resultArr[] = array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        );
    }
    $jsonApp = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
    // Format and print JSON data
    echo "<pre>" . prettyPrint($jsonApp) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderful. Thank you so much! I think I just wasn't thinking logically ;)
1

In your while loop, you're constantly re-asigning values to $jsonApp. I would recommend adding the values more like this:

$getApp = "SELECT * FROM tundra.apps WHERE app_key = '" . $api_key . "'";
$appData = $dbConnection->query($getApp);

if ($appData->num_rows > 0){ // Check if app_key exists
    for($i=0;$row = $appData->fetch_assoc();i++) { // While retrieving rows
        $jsonApp[i] = array( // Encode the row data
            "app_name" => $row['app_name'],
            "app_theme" => array(
                "primary_color" => $row['app_primary_color'],
                "primary_color_dark" => $row['app_primary_dark_color'],
                "accent_color" => $row['app_accent_color'],
            ),
            "app_navigation" => $row['app_navigation'],
            "author_info" => array(
                "author_name" => $row['app_author_name'],
                "author_bio" => $row['app_author_bio'],
                "links" => array(
                    "website" => $row['app_author_website'],
                    "googleplus" => $row['app_author_gplus'],
                    "twitter" => $row['app_author_twitter'],
                    "dribble" => $row['app_author_dribble'],
                    "behance" => $row['app_author_behance'],
                )
            ),
            "app_status" => $row['app_status']
        );
    }
    $json = json_encode($jsonApp,JSON_UNESCAPED_SLASHES);
    // Format and print JSON data
    echo "<pre>" . prettyPrint($json) . "</pre>";
} else { // No key found, encode error
    $jsonError = json_encode(
    array(
        array(
            "error" => array(
                "code" => "8",
                "message" => "Invalid API key specified"
            )
        )
    ), JSON_UNESCAPED_SLASHES);
    echo "<pre>" . prettyPrint($jsonError) . "</pre>";
}

This should show a JSON array, with each element in the array representing an individual app entry.

1 Comment

This approach seems logical by reading your code, but if I implement it, I get an HTTP 500 error. I haven't been able to tell what is wrong syntactically, if anything.
0

This is the format of JSON. You can not output different shapes. However, when decoding this JSON output, you can either decode objcet or array.

$object = json_decode($json);

$array = json_decode($json, true);

2 Comments

@LeoWilson not solve because issue is not interest the code. issue interested of read client this json output.
This doesn't seem to apply to my situation.
0

I believe it's because on line 6 of your example you're assigning the output of json_encode to the $jsonApp variable. It would be easier to use an array like so.

$jsonApp[] = array(

And then use json_encode at the end.

echo "<pre>" . prettyPrint(json_encode($jsonApp)) . "</pre>";

1 Comment

This would display invalid JSON, since it would only concatenate strings, not combine the values in an array, which might crash apps using the API.

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.