无法打印多维数组

时间:2016-07-11 06:46:10

标签: php json

我的要求是访问json响应,将其存储在php变量中,以便我将这些变量插入到数据库中。这是我的代码

$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>";
}

无法获取迭代期间分配的值

示例: $ array [0] ['promoId']正在运行 $ array [$ x] ['promoId']无法正常工作。

Json样本请求:

[{"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"},

请建议。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

$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>";
}

使用foreach()是迭代数组的正确方法。

另请注意,您提供的示例JSON使用promo_id而不是PromoID,因此您需要$value['promo_id']