CodeLobster IDE
http://codelobster.com/forum/

Search in a multidimensional array and get the key?
http://codelobster.com/forum/viewtopic.php?f=3&t=24605
Page 1 of 1

Author:  PerterP [ Thu May 23, 2019 6:38 am ]
Post subject:  Search in a multidimensional array and get the key?

Hello everyone, I was wondering if someone could explain to me how I could search in a multidimensional array and get the key? mp3 ringtones

Here is the example array:
Code:
Quote:
$data = array(
0 => array(
'name' => 'name one',
'lastname' => 'last name one',
info => array(
'tag' => 'some tag',
'itemId' => 'item id one'
)

),
1 => array(
'name' => 'name two',
'lastname' => 'last name two',
info => array(
'tag' => 'some tag',
'itemId' => 'item id two'
)

)
);

Free ringtones download at: https://phoneringtones.info/
I want to search for "item id two" and get the array key of 1, or if I searched for "item id one" then I get the key 0.
Sorry for my bad English, I hope someone will help me.

Author:  Admin [ Mon Jun 03, 2019 9:47 am ]
Post subject:  Re: Search in a multidimensional array and get the key?

Hi.

Please, look at our several samples:

Code:
$data = array(
0 => array(
'name' => 'name one',
'lastname' => 'last name one',
info => array(
'tag' => 'some tag',
'itemId' => 'item id one'
)

),
1 => array(
'name' => 'name two',
'lastname' => 'last name two',
info => array(
'tag' => 'some tag',
'itemId' => 'item id two'
)

)
);


/*
Example 1
   If all elements of the array have the same structure
*/
function search($data,$value){
    foreach ($data as $key => $val) {
        if(in_array($value,$val['info'])){
            return $key;
        }
    }
    return -1;
}

$key = search($data,'item id one');
if($key !== -1){
    echo "Array key is ".$key;
}else{
    echo "Key not found";
}


/*
Example 2
If all the elements of the array have a different structure
*/
function search2($data,$value,$k=-1){
    foreach ($data as $key => $val) {
        if(is_array($val)){
            $k = search2($val,$value,$k);
        }
        if($k !== -1){
            break;
        }else if($val == $value){
            $k= $key;
            break;
        }
       
    }
    return $k;
}




$key = search($data,'item id one');
if($key !== -1){
    echo "Array key is ".$key;
}else{
    echo "Key not found";
}



Regards,
Codelobster Team.

Page 1 of 1 All times are UTC
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
http://www.phpbb.com/