user3762051 user3762051 - 4 months ago 20
PHP Question

Unable to print multi dimensional arrays

My requirement is to access json response, store it in php variable so that i will insert those variables into database. Here's my code

$jsondata = file_get_contents('dealdetails.json');
$array = json_decode($jsondata, true);
$arrlength = count($array);
echo $arrlength;

for ($x = 0; $x < $arrlength; $x++)
{
//echo $x;
$PromoID = $array[$x]['PromoID'];
$OfferID = $array[$x]['OfferID'];
$OfferName = $array[$x]['OfferName'];
$Type = $array[$x]['Type'];
$Code = $array[$x]['Code'];
$Title = $array[$x]['Title'];
$Description = $array[$x]['Description'];
$Category = $array[$x]['Category'];
$OfferPage = $array[$x]['OfferPage'];
$DateAdded = $array[$x]['DateAdded'];
$Expiry = $array[$x]['Expiry'];

echo "<br>";
}


Unable to get the values assigned during iteration

Example :
$array[0]['promoId'] is working
Where as $array[$x]['promoId'] is not working.

Json sample request :

[{"featured":"0","exclusive":"1","promo_id":"xxx","offer_id":"x","offer_name":"xxx","coupon_title":"xx","category":"","coupon_description":"","coupon_type":"Coupon","coupon_code":"xxx","ref_id":"xxx","link":"xxx","coupon_expiry":"2017-03-31","added":"2016-01-05","preview_url":"http:\/\/www.stalkbuylove.com\/","store_link":"http:\/\/tracking.vcommission.com\/aff_c?offer_id=230&aff_id=43367"},
[{"featured":"0","exclusive":"1","promo_id":"xxx","offer_id":"x","offer_name":"xxx","coupon_title":"xx","category":"","coupon_description":"","coupon_type":"Coupon","coupon_code":"xxx","ref_id":"xxx","link":"xxx","coupon_expiry":"2017-03-31","added":"2016-01-05","preview_url":"http:\/\/www.stalkbuylove.com\/","store_link":"http:\/\/tracking.vcommission.com\/aff_c?offer_id=230&aff_id=43367"},


Please suggest.

Answer

Try something like this:

$jsondata = file_get_contents('dealdetails.json');
$array = json_decode($jsondata, true);

foreach ($array as $key => $value)
{
    //print_r($value);

    echo $value['PromoID'];
    $PromoID = $value['PromoID'];
    $OfferID = $value['OfferID'];
    $OfferName = $value['OfferName'];
    $Type = $value['Type'];
    $Code = $value['Code'];
    $Title = $value['Title'];
    $Description = $value['Description'];
    $Category = $value['Category'];
    $OfferPage = $value['OfferPage'];
    $DateAdded = $value['DateAdded'];
    $Expiry = $value['Expiry'];

    echo "<br>";
}

Using foreach() is the proper way to iterate through an array.

Also note that the sample JSON you provided uses promo_id instead of PromoID, so you'd want $value['promo_id'].