1

So I have an array ($items) which has about 900 items in it. What I'm trying to do is, for the items that are read ($key["status"] == 1) which is about 300 items -> push those into a second array ($lifeSpanArray) with two attributes (added_date and read_date).

For some reason, when I try to push items into the lifespan array, I only have one item. Like I said, there are around 300 items that are status read - and I can dump those out, so I believe I am making a mistake with building my lifeSpanArray and pushing into it.

Any help much appreciated!

$items = $pocket->retrieve($params, $accessToken);
$numberArticles = count($items["list"]);
$hasRead = 0;
$hasNotRead = 0;

$readDatesArray = array();
$lifeSpanArray = array();


foreach ($items['list'] as $key) {

    if ($key["status"] == 1) {
        $hasRead++;
        $timeAdded = date('m/d/Y', $key["time_added"]); 
        $dateRead = date('m/d/Y', $key["time_read"]);

        // Where the problem is - only one item added
        $lifeSpanArray['timeAdded'] = $timeAdded;
        $lifeSpanArray['timeRead'] = $dateRead;

        //Push into the read dates array
        array_push($readDatesArray, $dateRead);

    }
    else {
        $hasNotRead++;
    }

}

var_dump($lifeSpanArray);

2 Answers 2

2

As you are overwriting your $lifeSpanArray array on each iteration you're must be getting only last entry so what you need is a two-dimension array,

Change this,

//Push into lifespan array
$lifeSpanArray['timeAdded'] = $timeAdded;
$lifeSpanArray['timeRead'] = $dateRead;

to,

 $lifeSpanArray[] = array('timeAdded' => $timeAdded,'timeRead' => $dateRead);
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, that is obvious, rewriting it each time. THANK YOU!
Can you provide us the $lifeSpanArray array you getting. Also I will recommended you to post a question for it.
Here is the question stackoverflow.com/questions/24759729/… Thanks Rikesh, much appreciated!
0
$lifeSpanArray['timeAdded'] = $timeAdded;
$lifeSpanArray['timeRead'] = $dateRead;

For the above code, you are actually assigning a scalar value to $lifeSpanArray['timeAdded'] and $lifeSpanArray['timeRead'].

To treat them as array and push values to them, you should first initialize timeAdded and timeRead as arrays first:

$lifeSpanArray = array(
    'timeAdded' => array(),
    'timeRead' => array()
);

And pushing values to them within the foreach loop:

$lifeSpanArray['timeAdded'][] = $timeAdded;
$lifeSpanArray['timeRead'][] = $dateRead;

Comments

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.