简体   繁体   中英

Form date from foreach loop through object

So I have an array of objects that looks like this:

credit_cards[[0] => {expiration_date: {year: "17", month: "04"}]

What I try to do is somethings like this:

$years = [];
$months = [];
$dates = [];
foreach ($clients->settings->credit_cards as $key => $value){
                        $years[] = $value->expiration_date->year;
                        $months[] = $value->expiration_date->month;
                    }

I need to loop through every credit card in that array and make an array $dates that should form a basic date by concatenating years and months. So in this case it should look like this: $dates = ['2017-04'] . But I have no idea how to do this. Any help is welcomed and some explanation if you may so I can understand how to do this in the future.

You can just add the dates with a minor amount of work. create a parseable string that represents your Month / Year . Then put it in php's strtotime() . That integer representing seconds since the epoch is the 2nd argument to format the four digit date -dash- month that you are looking for.

$years[] = $value->expiration_date->year;
$months[] = $value->expiration_date->month);
$my = $value->expiration_date->month.'/'.$value->expiration_date->year;
$dates[] = date('Y-m', strtotime($my));

You're looking for the concatenate operator: . ( More info here. ) You can build a formatted date string and pass it to strtotime like WEBjuju's answer, or move directly to using the concatenation.

$years[] = $value->expiration_date->year;
$months[] = $value->expiration_date->month;
$dates[] = $value->expiration_date->year . '-' . $value->expiration_date->month;

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