[英]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 就像我只想保留$ array ['Result'] ['Hotels'] [1]并保留其余索引
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). 您可以使用array_intersect_key函数创建具有所需键(键)的数组。 In this case
[1=>null]
; 在这种情况下
[1=>null]
;
$array['Result']['Hotels'] = array_intersect_key($array['Result']['Hotels'], [1=>null]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.