将找到的数组键转换为数组

时间:2013-09-07 13:49:06

标签: php arrays

我有这个数组

$array = array(
    "one" => "bar",
    "two"    => "21",
    "three"    => "22",
    "four"    => "25",
    "five" => array(
         "xxxxxxxxxxxxxxxxxx" => array(
             "ar1" => "food",
             "ar2" => "dr",
             "ar3" => "ch",
             "ar4" => "ju"
         ),
        "yyyyyyyyyyyyyyyyyyyy" => array(
             "ar1" => "food",
             "ar2" => "dr",
             "ar3" => "ch",
             "ar4" => "ju"
         )),
    "six" => "et",
    "seven" => "op",
    "eight" => "hjs",
    "nine" => array(
         "1" => array(
             "ar5" => "food",
             "ar87" => "dr",
             "ar21" => "ch",
             "ar443" => "ju"
         ),
         "2" => array(
             "73" => "food",
             "82" => "dr",
             "90" => "ch",
             "2123" => "ju"
         )),
    "ten" => "bar",
    "eleven" => "bar",
    "twelve" => "bar"
);

我找到了像这样的给定级别的所有数组键

foreach ($array['five'] as $keyed=> $user) {
foreach ($user as $key => $value) {
       echo "Key: $key; Value: $value Keyed: $keyed<br />\n";
}
}

但是,我想获得所有找到的数组键,以便在array_key_exists中使用,所以我需要将找到的键转换为数组。我正在尝试使用此数组

function the_keys($val){
foreach ($val['five'] as $keyed=> $user) {
foreach ($user as $key => $value) {
    $keyed = array();
}
}
}

但即便如此,也没有按照我的想法将找到的密钥强制转换为数组。我需要做什么才能将找到的密钥强制转换为数组?

2 个答案:

答案 0 :(得分:3)

要获取$val['five']的所有密钥,您可以使用array_keys()

$keyed = array_keys($val['five']);

在这种情况下你不需要循环。

答案 1 :(得分:0)

也许这会解决你的问题

foreach($val['five'] as $arrFive) {
    //Here you have both arrays
    foreach($arrFive as $arrXXXX) {
        //Parse array with index xxxx
    }
    foreach($arrFive as $arrYYYY) {
        //Parse array with index yyyy
    }
}