CHarris
CHarris

Reputation: 2793

Why is my JSON Array not being returned in the correct format?

When I echo $json2 my JSON Array is being returned like :

[{"contact_phonenumber":"12345"}][{"contact_phonenumber":"67890"}][{"contact_phonenumber":"123456"}][{"contact_phonenumber":"78901"}][{"contact_phonenumber":"234567"}][{"contact_phonenumber":"8901234"}]

It doesn't look like a JSON Array to me, I'm sure there's something wrong with my loop - maybe because the while is nested in the for each or something but even when I change it I keep getting the same result. Can you help?

I want it my JSON array to be like :

[{"contact_phonenumber":"12345"}, {"contact_phonenumber":"67890"},
 {"contact_phonenumber":"123456"}, {"contact_phonenumber":"78901"},{"contact_phonenumber":"234567"}, {"contact_phonenumber":"8901234"}]

Here's my code:

<?php

require('dbConnect.php');

//this is the username in the user table
$Number = "+353872934480";

// get the username of the user in the user table, then get the matching user_id in the user table
// so we can check contacts against it 
$query = "SELECT * FROM user WHERE username = ?";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param('s', $Number) or die("MySQLi-stmt binding failed " . $stmt->error);
$stmt->execute() or die("MySQLi-stmt execute failed " . $stmt->error);
$result = $stmt->get_result();

while($row = $result->fetch_assoc()) {

    //this is the corresponding user_id in the user table of the user
    $user_id = $row["user_id"];
}

//post all contacts for user_id as a JSON array
$phonenumberofcontact = '["+11111","+222222","12345","67890","123456","78901","234567","8901234"]';
$array = json_decode($phonenumberofcontact);

//We want to check if contacts of user_id are also users of the app. 
$query = "SELECT * FROM user WHERE username = ?";
$stmt2 = $con->prepare($query) or die(mysqli_error($con));
$stmt2->bind_param('s', $phonenumberofcontact) or die("MySQLi-stmt binding failed " . $stmt->error);

//for each value, call it $phonenumberofcontact
foreach($array as $value) {
    $phonenumberofcontact = $value;

    $stmt2->execute() or die("MySQLi-stmt execute failed " . $stmt2->error);

    //match the phone numbers in the JSON Array against those in the user table
    $result2 = $stmt2->get_result();

    while($row = $result2->fetch_assoc()) {

        //make an array called $results
        //this is a matching number in user table and in the JSON Array
        //call this username contact_phonenumber
        $results = array();

        $results[] = array(
            'contact_phonenumber' => $row['username']
        );


        $json2 = json_encode($results);
        echo $json2;

    }
}

EDIT : Much obliged for your help but now when I do as most of your answers suggest - declaring $results and echoing json outside while loop, I get the following:

[][][{"contact_phonenumber":"12345"}][{"contact_phonenumber":"67890"}][{"contact_phonenumber":"123456"}][{"contact_phonenumber":"78901"}][{"contact_phonenumber":"234567"}][{"contact_phonenumber":"8901234"}]

Do you know how I can get just the matching numbers, without the empty brackets? And also, should only be square brackets at the beginning and end - as a JSON array would be.

Here's my updated code :

<?php

require('dbConnect.php');

//this is the username in the user table
$Number = "+353872934480";

// get the username of the user in the user table, then get the matching user_id in the user table
                // so we can check contacts against it 
                $query = "SELECT * FROM user WHERE username = ?";
                $stmt = $con->prepare($query) or die(mysqli_error($con));
                $stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
                $stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
                $result = $stmt->get_result();

            while ($row = $result->fetch_assoc()) {

            //this is the corresponding user_id in the user table of the user
            $user_id = $row["user_id"];
            }

//post all contacts for user_id as a JSON array
$phonenumberofcontact ='["+11111","+222222","12345","67890","123456","78901","234567","8901234"]';
$array = json_decode($phonenumberofcontact);

//We want to check if contacts of user_id are also users of the app. 
 $query = "SELECT * FROM user WHERE username = ?";
 $stmt2 = $con->prepare($query) or die(mysqli_error($con));
 $stmt2->bind_param('s', $phonenumberofcontact) or die ("MySQLi-stmt binding failed ".$stmt->error);

 //for each value, call it $phonenumberofcontact
    foreach ($array as $value)
    {
                $phonenumberofcontact = $value;

$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

//match the phone numbers in the JSON Array against those in the user table
     $result2 = $stmt2->get_result(); 
            //make an array called $results
            //this is a matching number in user table and in the JSON Array
            //call this username contact_phonenumber
$results = array();
while ($row = $result2->fetch_assoc()) {
    $results[] = array('contact_phonenumber' => $row['username']);//remove extra ,
}
$json2 = json_encode($results);
echo $json2;

    }

        ?>

Upvotes: 1

Views: 106

Answers (4)

Because you echo your JSON string inside foreach loop. Try this-

    <?php

    require('dbConnect.php');

    //this is the username in the user table
    $Number = "+353872934480";

    // get the username of the user in the user table, then get the matching user_id in the user table
                    // so we can check contacts against it 
                    $query = "SELECT * FROM user WHERE username = ?";
                    $stmt = $con->prepare($query) or die(mysqli_error($con));
                    $stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
                    $stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
                    $result = $stmt->get_result();

                while ($row = $result->fetch_assoc()) {

                //this is the corresponding user_id in the user table of the user
                $user_id = $row["user_id"];
                }

    //post all contacts for user_id as a JSON array
    $phonenumberofcontact ='["+11111","+222222","12345","67890","123456","78901","234567","8901234"]';
    $array = json_decode($phonenumberofcontact);

    //We want to check if contacts of user_id are also users of the app. 
     $query = "SELECT * FROM user WHERE username = ?";
     $stmt2 = $con->prepare($query) or die(mysqli_error($con));
     $stmt2->bind_param('s', $phonenumberofcontact) or die ("MySQLi-stmt binding failed ".$stmt->error);

     //for each value, call it $phonenumberofcontact
$i = 0;
$tempArray = array();
        foreach ($array as $value)
        {
                    $phonenumberofcontact = $value;

    $stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

    //match the phone numbers in the JSON Array against those in the user table
         $result2 = $stmt2->get_result(); 

                while ($row = $result2->fetch_assoc()) {

                //make an array called $results
                //this is a matching number in user table and in the JSON Array
                //call this username contact_phonenumber
        $results = array();

                        $results[] = array(
             'contact_phonenumber' => $row['username'], 
             );


               $tempArray[$i] = $results;
    $i++;
        }
$json2 = json_encode($results); 
echo $json2;
        }

            ?>

Upvotes: 0

yoeunes
yoeunes

Reputation: 2945

declare the results array outside of the while loop like this:

$results = array();
foreach ($array as $value)
{
    $phonenumberofcontact = $value;

    $stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);

    $result2 = $stmt2->get_result();

    while ($row = $result2->fetch_assoc()) {
        if(!empty($row['username'])) {
            $results[] = array('contact_phonenumber' => $row['username']);//remove extra ,
        }
    }
}

$json2 = json_encode($results);
echo $json2;

Upvotes: 5

Canis
Canis

Reputation: 4400

In the following part of the code you need to rearrange a few variables to have the desired effect:

$results = array();  // Move this outside the loop

while ($row = $result2->fetch_assoc()) {
    $results[] = array("contact_phonenumber" => $row["username"]); 
}

// As well as these two line
$json2 = json_encode($results); 
echo $json2;

Upvotes: 2

Manish Kumar
Manish Kumar

Reputation: 581

May be you can change your while block something like this:

$results = array();

while ($row = $result2->fetch_assoc()) {
    //make an array called $results
    //this is a matching number in user table and in the JSON Array
    //call this username contact_phonenumber
        $results[] = array(
         'contact_phonenumber' => $row['username'], 
         );
    }

    $json2 = json_encode($results); 
    echo $json2;

Upvotes: 1

Related Questions