简体   繁体   中英

Access MySql array by column name

My query looks like this:

SELECT * FROM tblName WHERE btn_group_id = 1 ;

Also I have array of languages $langs = array(5,7,19) the same in btn_lang_id

$btn = Array
(
    [0] => Array
        (
            [btn_id] => 1
            [btn_group_id] => 1
            [btn_lang_id] => 5
            [btn_text] => aaa1
        )

    [1] => Array
        (
            [btn_id] => 2
            [btn_group_id] => 1
            [btn_lang_id] => 7
            [btn_text] => bbb2
        )

    [2] => Array
        (
            [btn_id] => 3
            [btn_group_id] => 1
            [btn_lang_id] => 19
            [btn_text] => ccc3
        )
)

My question is how I can use this array to echo data by using btn_lang_id

foreach ($langs as $lang){
echo $btn[$lang['lang_id']]['btn_text'];
}

I want the above 3 arrays of $btn accessed by language id not by index 0,1,2. I there any way?

You can create an array with the "btn_lang_id" as a key using the following code:

<?php
$langs = array(5,7,19);

$btn = array(
    '0' => array(
            'btn_id' => 1,
            'btn_group_id' => 1,
            'btn_lang_id' => 5,
            'btn_text' => 'aaa1',
        ),
    '1' => array(
            'btn_id' => 2,
            'btn_group_id' => 1,
            'btn_lang_id' => 7,
            'btn_text' => 'bbb2',
        ),
    '2' => array(
            'btn_id' => 3,
            'btn_group_id' => 1,
            'btn_lang_id' => 19,
            'btn_text' => 'ccc3',
        ),
);

$customArr = array();   
foreach($langs as $key=>$value){
  $customArr[$value] = $btn[$key];
}
print_R($customArr);
?>

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