简体   繁体   中英

php get value of array from key name

I have different array name with several names => values inside it.

in my file shortcode-config.php:

$shortcodes['video_section'] = array(
    'no_preview' => true,
    'params' => 'xxx',
    'shortcode' => '[sc1][/sc1]',
    'popup_title' => __('Video Section', THEME_NAME),
    'shortcode_icon' => __('li_video')
);

$shortcodes['image_section'] = array(
    'no_preview' => true,
    'params' => 'yyy',
    'shortcode' => '[sc2][/sc2]',
    'popup_title' => __('Image Section', THEME_NAME),
    'shortcode_icon' => __('li_image')
);

I want to get the value of shortcode_icon . I know the name of the array and I just want the value of a desired aray name.

For example I tried this without success:

define( 'TINYMCE_DIR', plugin_dir_path( __FILE__ ) .'tinymce' );
require_once( TINYMCE_DIR . '/shortcodes-config.php' );

$name = 'video_section';
$icon = $shortcodes[$name]['shortcode_icon'];

Does I need to use a foreach loop or can I access to this just with name?

You can access it with both methods. First one with loop is used if you don't really now the exact name and where it is or if the array is dynamic. Second one if everything is static and you know the exact name and in which dimension it is.

So it works with

$name = 'video_section';
$icon = $shortcodes[$name]['shortcode_icon'];

You can access it via named indexes or in a loop. See examples below:

$name = 'video_section';
$icon = $shortcodes[$name]['shortcode_icon'];

var_dump($icon)

returns string(8) "li_video"

As $shortcodes is an array anyway, you can access any elements store in there using a loop, such as the video_section array and the image_selection array

foreach ($shortcodes as $code) {
    if ($code == "video_section") {
        //handle video section
    }
    if ($code == "image_section") {
        //handle video section
    }
}

You also appear to be missing a semi colon at the end of the $name variable declaration.

Turning on errors might be helpful:

error_reporting(E_ALL); ini_set('display_errors', 'On');

Alternatively write a function that passes a $name argument, just make sure the array is accessible in the function / outside of the scope:

$return = getShortcode('video_section');

function getShortcode($name)
{
    return $shortcodes[$name]['shortcode_icon'];
}

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