Nyerere Nyerere - 3 months ago 18
JSON Question

parsing JSON url in PHP

i have a json data that i want to get it from my json array so that i can display the data on my php form:
Here is my json object,

{
"response": {
"result": {
"Contacts": {
"row": [
{
"no": "1",
"fl": [
{
"val": "CONTACTID",
"content": "144120000000079041"
},
{
"val": "First Name",
"content": "Tata"
},
{
"val": "Last Name",
"content": "Nyerere"
},
{
"val": "Email",
"content": "nyereredaniel@gmail.com"
},
{
"val": "Account Name",
"content": "null"
},
{
"val": "Phone",
"content": "null"
},
{
"val": "Mobile",
"content": "null"
}
]
},
{
"no": "2",
"fl": [
{
"val": "CONTACTID",
"content": "144120000000069001"
},
{
"val": "First Name",
"content": "null"
},
{
"val": "Last Name",
"content": "DANIEL NYERERE"
},
{
"val": "Email",
"content": "nyereredaniel@hotmail.com"
},
{
"val": "Account Name",
"content": "null"
},
{
"val": "Phone",
"content": "null"
},
{
"val": "Mobile",
"content": "null"
}
]
},
{
"no": "3",
"fl": [
{
"val": "CONTACTID",
"content": "144120000000065068"
},
{
"val": "First Name",
"content": "null"
},
{
"val": "Last Name",
"content": "Lawrence"
},
{
"val": "Email",
"content": "support@zohosupport.com"
},
{
"val": "ACCOUNTID",
"content": "144120000000065066"
},
{
"val": "Account Name",
"content": "Zoho"
},
{
"val": "Phone",
"content": "1 888 900 9646"
},
{
"val": "Mobile",
"content": "null"
}
]
}
]
}
},
"uri": "/api/json/contacts/getrecords"
}


}

I need to display those data on my php form , and here is the sample i have tried but i'm stuck with it:`

<?php
$url = "my url";
$json = file_get_contents($url);
$json = json_decode($json, true);
$response = $json['response'];
$result = $response['result'];
$contact = $result['Contacts'];
$data = $contact['row'];
$name = $dat[0];
echo "Contact name: " . $name;
?>


I want to display the values of CONTACTID ,First Name ,Last Name ,Email into my php form
Anyone who can assist on that ,will appreciate a lot

Answer

Here is simple way, i made a helper function to extract value from array. Look at this example:

<?php
$url      = "my url";
$json     = file_get_contents($url);
$json     = json_decode($json, true);
$response = $json['response'];
$result   = $response['result'];
$contact  = $result['Contacts'];
$data     = $contact['row'];

// Helper Function
function getValByName($name, $array)
{
    foreach ($array as $row) {
        if ($row['val'] == $name) {
            return $row['content'];
        }
    }

    return '';
}

foreach ($data as $row) {
    $FirstName = getValByName('First Name', $row['fl']);
    $ContactId = getValByName('CONTACTID', $row['fl']);
    $LastName  = getValByName('Last Name', $row['fl']);
    $Email     = getValByName('Email', $row['fl']);
    $Phone     = getValByName('Phone', $row['fl']);
    $Mobile    = getValByName('Mobile', $row['fl']);

    echo $FirstName . ' ' . $LastName . '<br/>';
}