简体   繁体   中英

PHP get variable in function from foreach loop

I am working on some plugin in wordpress and I have following array and foreach loop with function in it.

Problem is that somehow I always getting $locale_key variable same as $code when $locale_key variable is inside function.

Please help.

$languages = array(
    array('af', 'af', 'Afrikaans'),
    array('ar', 'ar', 'العربية', 'rtl'),
    array('az', 'az', 'Azərbaycan'),
    array('be', 'bel', 'Беларуская мова'),
    array('bg', 'bg_BG', 'български'),
    array('bs', 'bs_BA', 'Bosanski'),
    array('ca', 'ca', 'Català'),
    array('cs', 'cs_CZ', 'Čeština'));

$lang = $_SESSION['lang'];

foreach ($languages as $key => $value) {
    $locale_key = $languages[$key][1];
    $code = $languages[$key][0];
    echo $locale_key; // Here i get for example "bs_BA"
    add_shortcode( $code, function($atts, $content = null, $locale_key) {
        global $lang;
        echo $locale_key; // And then here i get "bs"
        if ($lang == $locale_key) {
            return $content;
        }
    }); 
}

Try:

$languages = array(
    array('af', 'af', 'Afrikaans'),
    array('ar', 'ar', 'العربية', 'rtl'),
    array('az', 'az', 'Azərbaycan'),
    array('be', 'bel', 'Беларуская мова'),
    array('bg', 'bg_BG', 'български'),
    array('bs', 'bs_BA', 'Bosanski'),
    array('ca', 'ca', 'Català'),
    array('cs', 'cs_CZ', 'Čeština'));

$lang = $_SESSION['lang'];

foreach ($languages as $key => $value) {
    $locale_key = $value[1];
    $code       = $value[0];
    add_shortcode( $code, function($atts, $content = null, $locale_key) {
        global $lang;
        if ($lang == $locale_key) {
            return $content;
        }
    }); 
}

When you use foreach($array as $key => $value) you can access the index via $key and the corresponding value via $value (even if that is an array too).

<?php
$array = [
    [1, 2, 3],
    [3, 4, 5],
];

foreach ($array as list($a, $b, $c)) {
    // $a enthält das erste Element des verschachtelten Arrays
    // und $b enthält das zweite Element
    echo "A: $a; B: $b; C: $c\n";
}
?>

Try something like above, im sure you will find the solution.

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