Showing posts with label PHP JSON. Show all posts
Showing posts with label PHP JSON. Show all posts

Friday, 5 October 2018

PHP - PARSING JSON DATA

PHP - CREATING JSON DATA

Using below PHP snippet you can create JSON data. This will come handy when you are creating web services for mobile apps.

Monday, 24 September 2018

POSTing json data with php cURL

<?php

$params = array(

    "id" => 1,

    "name" => "Pritom Kumar Mondal"

);

$param = json_encode($params);

$ch   = curl_init("http://localhost/api_server/user");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

    'Content-Type: application/json',

    'Content-Length: ' . strlen($param))

);

$response = curl_exec($ch);

print_r($response);

?>

Wednesday, 12 September 2018

Converting an array to JSON data with PHP

PHP's json_encode function converts a PHP variable into a JSON string which can then be used in Javascript, for example using jQuery's JSON functions. This is easy to do and I'll be combining the two together in tomorrow's post to show how to fetch data from a MySQL database with PHP into Javascript via JSON.

Converting a PHP array to JSON

Assuming data had been selected from the database using my example fruit table into a multidimensional array with PDO::fetchAll using "SELECT * FROM fruit WHERE name = 'Apple'", the array would look like so:
Array
(
    [0] => Array
        (
            [fruit_id] => 1
            [name] => Apple
            [variety] => Red Delicious
        )

    [1] => Array
        (
            [fruit_id] => 6
            [name] => Apple
            [variety] => Cox's Orange Pippin
        )

    [2] => Array
        (
            [fruit_id] => 7
            [name] => Apple
            [variety] => Granny Smith
        )

)
If the array was called $data, to convert and echo to the browser as JSON do this:
echo json_encode($data);
The resulting JSON encoded string would look like so:
[{"fruit_id":"1","name":"Apple","variety":"Red Delicious"},{"fruit_id":"6","name":"Apple","variety":"Cox's Orange Pippin"},{"fruit_id":"7","name":"Apple","variety":"Granny Smith"}]

Version requirements and further reading

PHP 5.2.0 or higher comes bundled with the JSON functions. Prior to 5.2.0 the PECL extension needs to be installed. Read the PHP JSON manual pages for more details.
There will be another post tomorrow which ties together three posts over the last few days and shows how to load JSON data with jQuery, PHP and MySQL.
 

Related posts:

Thursday, 6 September 2018

PHP: How to access the values of the array elements using the array index

How to access array element values using array-index?
<?
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);

echo $arr['dynamic']['pageCount']; // working
echo $arr[0]['pageCount']; // not working
?>

I will not know what is there in 'dynamic', so i want to access pageCount values dynamically?

array_values is function you are looking for
Examples:
<?php
$json = '{
    "dynamic":{
       "pageCount":"12",
       "tableCount":"1"
    }
}';

$arr = json_decode($json, true);
echo $arr['dynamic']['pageCount']; // working

$arr = array_values($arr);
echo $arr[0]['pageCount']; // NOW working

?>

Monday, 3 September 2018

PHPjson_encode does not return anything

I am trying to convert my MYSQL table data into JSON. I am trying with json_encode(). But it does not work. It does not return anything. I have checked the console,doesn't even throw any errors. What am i missing?

<?php
    //open connection to mysql db
    $connection = mysqli_connect("localhost","root","","maps") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = "select * from locations";
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array
    $emparray[] = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);
?>


try this
while ( $row = $result->fetch_assoc() ){
    $emparray[] = json_encode($row);
}
echo json_encode( $emparray );

or
while($row =mysqli_fetch_assoc($result))
{
   $emparray[] = json_encode($row);
}
echo json_encode($emparray);

or
$emparray = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $emparray );

instead of
 while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }
    echo json_encode($emparray);

With Php in a JSON array, how to retrieve the value of an element based on another associated value?

I use json_decode Php function to get a JSON array of countries datas.

{
    "Countries":
    [
        {
            "Code": "AD",
            "Name": "Andorre"
        },
        {
            "Code": "AE",
            "Name": "Émirats Arabes Unis"
        },
        {
            "Code": "AF",
            "Name": "Afghanistan"
        },
        {
            "Code": "AG",
            "Name": "Antigua-Et-Barbuda"
        },

If I want to retrieve the Code of the 1st element I can do:
$result = json_decode($sXML);

$final = $result->Countries[0]->Name;

And $final will have the value of 'Andorre'. But what if I want to retrieve the same value 'Andorre' using its correspoding Code ?
Is it possible to do it ? I know there is an option for the json_function() to obtain an associative array instead of a JSON array, but how would you use it to get the value 'Andorre' using its Code ?
Thank you

Here we are using two function for achieving this array_column and array_combine to retrieve the expected output.
<?php
ini_set('display_errors', 1);
$string='{
    "Countries":
    [
        {
            "Code": "AD",
            "Name": "Andorre"
        },
        {
            "Code": "AE",
            "Name": "Émirats Arabes Unis"
        },
        {
            "Code": "AF",
            "Name": "Afghanistan"
        },
        {
            "Code": "AG",
            "Name": "Antigua-Et-Barbuda"
        }
    ]
    }';
$array=json_decode($string,true);
$codes=  array_column($array["Countries"], "Code");//Retrieving column code
$names=  array_column($array["Countries"], "Name");//Retrieving column name
$data=  array_combine($codes, $names); //combining array with code as keys and names as values.
print_r($data);`

Output:
Array
(
    [AD] => Andorre
    [AE] => Émirats Arabes Unis
    [AF] => Afghanistan
    [AG] => Antigua-Et-Barbuda
)

Merge two complex objects in PHP

I have two data objects converted from JSON. both are quite deeply complex and I'd like to merge them in a similar fashion to how jQuery would merge two objects using extend.

example
JSON 1:
{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "misc": "0",
                ...
            },
            ...
        },
        ...
    },
    ...
}

JSON 2:
{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}

Merged into
{
    ...
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "value": "val",
                "misc": "1",
                ...
            },
            ...
        },
        ...
    },
    ...
}

What's the best way to approach this with PHP objects.

Decode each JSON string into an associative array, merge the results and re-encode
$a1 = json_decode( $json1, true );
$a2 = json_decode( $json2, true );

$res = array_merge_recursive( $a1, $a2 );

$resJson = json_encode( $res );

Update: If you have a specific merge requirement then you'll need to write your own merging function. I have written one below which fulfills your requirements as stated in the question. You may need to tweak it if you have other requirements you haven't mentioned.
<?php

$json1 = '
{
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "misc": "0"
            }
        },
        "lost":
        {
            "one": "hat",
            "two": "cat"
        }
    }
}';

$json2 = '
{
    "blah":
    {
        "lost": "gone",
        "params":
        {
            "foo":
            {
                "value": "val",
                "misc": "1"
            }
        }
    },
    "num_array": [12, 52, 38]
}';

$a1 = json_decode( $json1, true );
$a2 = json_decode( $json2, true );

/*
 * Recursive function that merges two associative arrays
 * - Unlike array_merge_recursive, a differing value for a key
 *   overwrites that key rather than creating an array with both values
 * - A scalar value will overwrite an array value
 */
function my_merge( $arr1, $arr2 )
{
    $keys = array_keys( $arr2 );
    foreach( $keys as $key ) {
        if( isset( $arr1[$key] )
            && is_array( $arr1[$key] )
            && is_array( $arr2[$key] )
        ) {
            $arr1[$key] = my_merge( $arr1[$key], $arr2[$key] );
        } else {
            $arr1[$key] = $arr2[$key];
        }
    }
    return $arr1;
}

$a3 = my_merge( $a1, $a2);
$json3 = json_encode( $a3 );
echo( $json3 );

/*
{
    "blah":
    {
        "params":
        {
            "foo":
            {
                "default": "bar",
                "misc":    "1",
                "value":   "val"
            }
        },
        "lost": "gone"
    },
    "num_array": [12,52,38]
}
*/

Friday, 31 August 2018

PHP - how to create an associative array from the database object and json_encode as an object instead of an array?

I am a newbie in PHP and developing an app using Yii. I have a database object where all I got all the records of a table. I wanted to create an associative array from that object and later encode that array in json_encode. However, my desired output,which is objects instead of array, is not coming. can anyone help, plz?

My code:
$info = array();
$category = Category::find()->all();
foreach($category as $key => $value) {
    $info[]=  array(
         "name" =>$value->name,
         "value" =>$value->description
    ) ;
}
echo json_encode($info,JSON_FORCE_OBJECT);

Output:
{"0":{"name":"test","value":"A"},"1":{"name":"test 2","value":"B"}}

Desired Output:
{"category":[{"name":"test","value":"A"},{"name":"test 2","value":"B"}]}


Try to use this:
$info2['category']=$info;
echo json_encode($info2);

Tuesday, 28 August 2018

PHP json does not show all related values

Hello I have this php code for printing json

<?php

include('databaseconnect.php');

$sql = "SELECT product_id,product_name FROM products WHERE product_id='1'";
$result = $conn->query($sql);

$sql2 = "SELECT GROUP_CONCAT(ss.Name,':',sv.value_s ) as Specifications FROM specifications ss, specification_value sv WHERE sv.specification_ID = ss.specification_ID AND sv.product_id =  '1'";
$fetch = $conn->query($sql2);

$sql3 = "select GROUP_CONCAT(v.name,':',vv.value) as variants from variant v,variant_value vv where v.variant_id=vv.variant_id and product_id='1'";
$fetch1 = $conn->query($sql3);

$json['products'] = array();

while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){

    $json['products'] = $row;

  }

$json['products']['specification'] = array();

while ($row = mysqli_fetch_assoc($fetch)){

    $specification_array  = explode(',', $row["Specifications"]);
    $speci_array = array();
    foreach($specification_array as $spec){
        $spec = explode(':',$spec);
        $speci_array[$spec[0]] = $spec[1];
    }
    $json['products']['specification'] = $speci_array;

    //array_push($json['products'],$row_temp);
   }

$json['products']['specification']['variants'] = array();

while ($row = mysqli_fetch_assoc($fetch1)){

    $variants_array  = explode(',', $row["variants"]);
    $vari_array = array();
    foreach($variants_array as $var){
        $var = explode(':',$var);
        $vari_array[$var[0]] = $var[1];
    }
    $json['products']['specification']['variants'] = $vari_array;

    //array_push($json['products'],$row_temp);
   }

echo Json_encode($json);

?>

and output of this is
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "long"
            }
        }
    }
}

but in this i have one more value for variant i.e. "size":"small" and that is not showing up. sorry for bad English please ask me for any clarification before answering
my desired output
{
    "products": {
        "product_id": "1",
        "product_name": "Face Wash",
        "specification": {
            "brand": "Python",
            "product_Description": "very good",
            "variants": {
                "size": "small"
                "size": "long"
            }
        }
    }
}


You can't add same key size twice. The previous key gets overwritten by later.

Thursday, 4 September 2014

What is the best way to return data in the JSON format from PHP?

If you are running PHP 5.2 or greater, you can use the built-in json_encode function to return JSON formatted data from PHP. Here is an example of it’s usage:

Example of returning JSON from PHP

$tennisArray = array('Djokovic' => 1, 'Federer' => 2, 
'Nadal' => 3, 'Murray' => 4);

echo json_encode($tennisArray);
The code above will output the JSON formatted data like this:
{"Djokovic":1,"Federer":2,"Nadal":3,"Murray":4}