无法访问对象属性php

时间:2016-11-23 13:08:00

标签: php

我在rewards-object.php文件中有以下对象:

<?php

$rewards_obj_data = array(
    array(
    'reward_id' => 0,
    'reward_mile_text' => "mile 0",
    'reward_title' => "Tag Connected Watch",
    'reward_img' => "../assets/rewards/rewards-1.jpg",
    'reward_apr' => "Representative 18.9% APR (variable)",
    'reward_cta_url' => "rewards/claimReward.jsp&rewardID=0"/* + auth cookie details */,
    ),
    array(
    'reward_id' => 1,
    'reward_mile_text' => "mile 1",
    'reward_title' => "Tag Connected Watch",
    'reward_img' => "../assets/rewards/rewards-1.jpg",
    'reward_apr' => "Representative 18.9% APR (variable)",
    ),    
    array(
    'reward_id' => 2,
    'reward_mile_text' => "mile 2",
    'reward_title' => "Tag Connected Watch",
    'reward_img' => "../assets/rewards/rewards-1.jpg",
    'reward_apr' => "Representative 18.9% APR (variable)",
    ),    
    array(
    'reward_id' => 3,
    'reward_mile_text' => "mile 3",
    'reward_title' => "Tag Connected Watch",
    'reward_img' => "../assets/rewards/rewards-1.jpg",
    'reward_apr' => "Representative 18.9% APR (variable)",
    ),    
    array(
    'reward_id' => 4,
    'reward_mile_text' => "mile 4",
    'reward_title' => "Tag Connected Watch",
    'reward_img' => "../assets/rewards/rewards-1.jpg",
    'reward_apr' => "Representative 18.9% APR (variable)",
    ),    
);

?>

我试图在另一个for循环中访问它的属性:

<?php
    require '../api/rewards-object.php';

   // in between here I make some API calls to retrive an array of objects which I have named $rewardsAPIResponse

    // parse http request
    $decode_rewardsAPIResponse = json_decode($rewardsAPIResponse);

    /* for loop */
    foreach($decode_rewardsAPIResponse as $key=>$value){

        $IdFromApi = $value->rewardID;

         $test = json_encode($rewards_obj_data[$IdFromApi]->reward_title);
        echo $test;
    };
?>

这里的想法是使用从API返回的对象的id来获取rewards-object.php文件中的对象。

目前如果我更换这一行:

     $test = json_encode($rewards_obj_data[$IdFromApi]->reward_id);
    echo $test;

使用:

     $test = json_encode($rewards_obj_data[$IdFromApi]);
    echo $test;

然后它抓取对象没问题!问题在于我尝试访问对象属性,例如reward_title。这里它返回一个null值。我一直在玩json_encode部分,因为我认为这可能是问题的所在,但到目前为止我所尝试的一切都无效。我出错了什么想法?

3 个答案:

答案 0 :(得分:1)

我没有看到物体,而是二维阵列。 将您的值设为$rewards_obj_data[$IdFromApi]['reward_title'];

答案 1 :(得分:1)

$ rewards_obj_data是一个数组,内容也是如此。但是你试图像对象那样访问它。它是一个数组,而不是一个对象。 这将是正确的方法:

$rewards_obj_data[$IdFromApi]['reward_id']

答案 2 :(得分:0)

您的数组不是对象。在PHP中,数组可能存在整数和字符串键,这可能就是混乱。

echo $rewards_obj_data[0]['reward_id']; // 0

foreach($rewards_obj_data as $value){
  echo $value['reward_id'];
}

// Convert array to to string, converting arrays to objects.
$json = json_encode($rewards_obj_data, JSON_FORCE_OBJECT);

// Convert json to a PHP object.
$data = json_decode($json);

foreach($data as $obj){
  echo $obj->reward_id;
}