Benjamin Liger Benjamin Liger - 17 days ago 10
PHP Question

Unable to access object property php

I have the following object in a rewards-object.php file:

<?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)",
),
);

?>


I am trying to access its properties in another for loop:

<?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;
};
?>


The idea here is to use the id of the objects that is returned from the API to fetch objects in the rewards-object.php file.

At the moment if I replace this line:

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


with:

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


Then it fetches the objects no problem! The problem lies with me trying to access the objects property such as
reward_title
. Here it returns me a value of null. I have been playing around with the json_encode part as I think that could be where the issue lies but so far everything i've tried doesn't work. Any ideas where i've gone wrong?

Answer

$rewards_obj_data is an array, and so is the content. But you try to access it like you would an object. Its an array, not an object. This would be the correct way:

$rewards_obj_data[$IdFromApi]['reward_id']