简体   繁体   English

php从键名获取数组的值

[英]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: 在我的文件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 . 我想获取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? 我需要使用一个foreach循环还是可以仅使用名称来访问它?

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. 如果您现在还不知道确切的名称和名称,或者数组是动态的,则使用第一个with循环。 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" 返回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 由于$ shortcodes是一个数组,因此您可以使用循环访问其中存储的任何元素,例如video_section数组和image_selection数组

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. 您也似乎在$ name变量声明的末尾缺少分号。

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: 或者编写一个传递$ name参数的函数,只需确保该数组可在作用域内的函数/中访问:

$return = getShortcode('video_section');

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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