除了数组中的一个索引之外,如何取消其余元素的设置

时间:2016-06-05 10:17:39

标签: php arrays

有一个数组我想取消其余的元素,除了数组中的一个索引

阵列

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

就像我想要只保留 $ array ['结果'] ['酒店'] [1] 并取消其余的索引

想要输出

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

我试过这个

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

3 个答案:

答案 0 :(得分:0)

我只需将所需元素复制出数组,然后忘记原始数组。

答案 1 :(得分:0)

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

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

}

答案 2 :(得分:0)

您可以使用{{3}}函数创建具有所需键(键)的数组。在这种情况下[1=>null];

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