简体   繁体   中英

How to unset rest of element except then one index in array

Have an array i want to unset rest of element except then one index in array

Array

$array = Array ( "Result" => Array ( "ResponseStatus" => 1, "Hotels" => Array ( Array ( "Rating" => 1, "Description" => "Description1" ), Array ( "Rating" => 2, "Description" => "Description2"), Array ( "Rating" => 4, "Description" => "Description3") ) ) );

Like i want keep only $array['Result']['Hotels'][1] and unset rest of index

Want Output

Array
(
    [Result] => Array
        (
            [ResponseStatus] => 1
            [Hotels] => Array
                (
                    [1] => Array
                        (
                            [Rating] => 2
                            [Description] => Description2
                        )
                )
        )
)

I have tried this

$arrayKey = 1;
foreach ($array['Result']['Hotels'] as $key => &$value) {
    if (!$key == $arrayKey) {
        unset($value[$key]);
    }
}

我只是将所需的元素从数组中复制出来,而忘记了原始数组。

$arrayKey = 1;
foreach ($array['Result']['Hotels'] as $key => &$value) {

    if ($key != $arrayKey) {
        unset($value[$key]);
    }

}

You can use array_intersect_key function creating an array with the desired key (keys). In this case [1=>null] ;

$array['Result']['Hotels'] = array_intersect_key($array['Result']['Hotels'], [1=>null]);

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