0

I've been trying to use a standard object to set up and hold items against days of the week

$day = new stdClass();
$days = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday');

The data is an array like this:

$activity = Array
(
    [0] => 1
    [1] => activity 1
    [2] => 1
    [3] => activity 2
    [4] => 3
    [5] => activity 5
    [6] => 4
    [7] => activity 7 ...(more entries)

First item is day of the week so Monday is 1 Tuesday is 2 etc

I want to create an object for each day. And then add the activities for the day to it. I then want to be able to iterate through each day taking out the activities one at a time and processing them. I tried this

for($x=0;$x<count($activity);$x+=2){
    $dayIs = $days[$activity[$x - 1]];
    $day->$dayIs->activity = $activity[$x+1];

This throws Cannot use object of type stdClass as array

Do I need to use a switch statement for each day and then do

$day->monday->activity = $activity[$x+1];

or is there some other way of doing this.

Also when I have the day set up how can I add multiple activities to it.

Sorry if this is an obvious thing. I can do this with arrays but I though it was time to have a go at using objects instead.

3
  • 2
    Does this answer your question? How do I dynamically write a PHP object property name? Commented Jul 7, 2021 at 9:49
  • thanks that answers my question Commented Jul 7, 2021 at 9:59
  • 2
    $dayIs = $days[$activity[$x - 1]]; this is wrong because on very first iteration where $x is 0, you're trying to get something from an index in $activity which doesn't exists i.e. $activity[- 1]; Commented Jul 7, 2021 at 10:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.