Last active
December 3, 2015 20:54
-
-
Save luclemo/1c76644325748be8bd7f to your computer and use it in GitHub Desktop.
Code snippet by Darcy to help me understand dynamic objects in PHP. Props taken from WordPress project (mdupuis)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP 5.4+ | |
// Dynamically generated images objects | |
// Properties | |
$props = array('ID', 'caption', 'title', 'alt', 'sizes'); | |
// Make an images object | |
$images = new stdClass(); | |
// Create three nested images objects with some initial data | |
$images->large = (object) array('size' => 'mosaic-large', 'field' => get_sub_field('image_1')); | |
$images->top = (object) array('size' => 'mosaic-small', 'field' => get_sub_field('image_2')); | |
$images->bottom = (object) array('size' => 'mosaic-small', 'field' => get_sub_field('image_3')); | |
// Iterate over images | |
foreach($images as $image => $data): | |
// Iterate over properties | |
foreach($props as $prop): | |
$images->{$image}->{$prop} = $data->field[$prop]; | |
endforeach; | |
// Add image data | |
$images->{$image}->url = $data->field['sizes'][$data->size]; | |
$images->{$image}->width = $data->field['sizes'][$data->size.'-width']; | |
$images->{$image}->height = $data->field['sizes'][$data->size.'-height']; | |
// Get rid of redundant image field data | |
unset($images->{$image}->field); | |
endforeach; | |
// Now you should have a nice $images object with all your info | |
print_r($images); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment