Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to run a clean up job on data in an array, specifically converting epoch time to YYYY-MM-DD.

I tried this function originally:

foreach ($data as $row) {
    $row['eventdate'] = date('Y-m-d', $row['eventdate']);
}

echo '<pre>';
print_r($data);
echo '</pre>';

However the foreach loop didn't update the data when I output it.

The following for loop did work:

for ($i=0; $i<count($data); $i++) {
    $data[$i]['eventdate'] = date('Y-m-d', $data[$i]['eventdate']);
}

Why did the first loop fail and the second work? Aren't they the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

When you're using a foreach loop in the way you currently are, foreach ($data as $row) {, $row is being used "by-value", not "by-reference".

Try updating to a reference by adding the & to the $row:

foreach ($data as &$row) {
    $row['eventdate'] = date('Y-m-d', $row['eventdate']);

Or, you can use the key/value method:

foreach ($data as $index => $row) {
    $data[$index]['eventdate'] = date('Y-m-d', $row['eventdate']);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...