user2656127
user2656127

Reputation: 665

Can't push all array items into a second array PHP

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);

Upvotes: 1

Views: 52

Answers (2)

Chris Lam
Chris Lam

Reputation: 3614

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

Upvotes: 0

Rikesh
Rikesh

Reputation: 26421

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);

Upvotes: 2

Related Questions