简体   繁体   中英

Get the first 4 digits of each element of an array

I have an array which i got from an sql database, and each element is saved as YYYY-MM-DD. but i only need the year of each element. My current code:

if(isset($_GET['date'])){
$dates= unserialize(urldecode($_GET['date']));
foreach($dates as $i){
$year = substr($i, 0, 4);
}}
print_r($year);

but when i run the code it only gives me the year of the first element

i already tried array_slice but that didnt work either

if(isset($_GET['date'])) {
    $dates= unserialize(urldecode($_GET['date']));
    $year = array();
    foreach($dates as $i) {
        $year[] = substr($i, 0, 4);
    }
}
print_r($year);

2 little changes that will fix it.

因为您的$year是一个变量,所以$year值将在每次迭代时被覆盖,尝试将$year定义为array()以便每次将值添加到新数组索引上

$year[] = substr($i, 0, 4);

If you would like each date's year, you should use them as you extract them. For example, you could put them in an array:

$years = array();
if (isset($_GET['date'])) {
    $dates= unserialize(urldecode($_GET['date']));
    foreach($dates as $i){
        $year = (int)substr($i, 0, 4);
        if (($year >= 1900) && ($year <= 2050))
            $years[] = $year;
    }
}
print_r($years);

Notice that you can also test the validity of your dates before appending the the array $years . You can, of course, also test the resulting array itself. You can also use them "on-the-fly" inside the foreach loop if you choose.

However, you cannot reassign the same variable a different value and expect it to be anything other than the last value assigned to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM