简体   繁体   中英

Rename PHP array keys in object oriented functions

This may seem like a trivial question, but I'm not sure how to search for this? Let me explain my problem in situ...


I currently have this object oriented php function...

class Gallery extends Methods {

    /**
     * Output image attachment source
     * @return void
    */
    public function img_src ($image_id,$size) {
        $attachment_src = wp_get_attachment_image_src( $image_id, $size );
        return $attachment_src;
    }

}


Then I'm creating these vars foreach of my images..

<?php

  $img['thumbnail'] = Gallery::img_src( $image->ID, 'thumbnail' );
  $img['medium']    = Gallery::img_src( $image->ID, 'medium'    );
  $img['large']     = Gallery::img_src( $image->ID, 'large'     );
  $img['full-size'] = Gallery::img_src( $image->ID, 'full-size' );

  exit( '<pre>' . print_r( $img['full-size'], true ));

?>


The exit pre print_r call above, see output below...

Array
(
    [0] => http://example.com/wp-content/uploads/2015/02/jorge-hernandez-farguell_0067.jpg
    [1] => 5760
    [2] => 3840
    [3] => 
)


So currently if I wanted to output the width which is array key 1, I have to do this...

$img['full-size'][1];
$img['full-size'][2];
$img['full-size'][3];


The current above array key structure is confusing because the integer keys mean nothing. So my million dollar question is.. can I some how rename my array keys so my array outputs like this...

Array
(
    [url] => http://example.com/wp-content/uploads/2015/02/jorge-hernandez-farguell_0067.jpg
    [width] => 5760
    [height] => 3840
    [3] => 
)


and in turn, I would like to be able to outout the data like this...

<?=$img['full-size']['url']?>
<?=$img['full-size']['width']?>
<?=$img['full-size']['height']?>


Can anyone help me with adjusting my top attach_src function to do this? Or can this not be done?

Thanks in advance! x


http://codex.wordpress.org/Function_Reference/wp_get_attachment_image_src

Since you already know what the indexes are in reference to, you can just rename them before you return the result. Check out the answer at: How to rename array keys in PHP?

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