在php中获取数组的子数组

我有一个数组 ($skus),看起来像这样;


$skus[0] = "hello";

$skus[1] = "world";

$skus[2] = "sky";

$skus[3] = "is";

$skus[4] = "blue";

我的问题是,如何根据另一个数组获取该数组的子集,即子集数组是;


$words = array(0,2,4);

这将返回给我一个数组["hello", "sky", "blue"],即


$return[0] = "hello";

$return[1] = "sky";

$return[2] = "blue";



慕莱坞森
浏览 299回答 2
2回答

互换的青春

你可以用array_intersect_key()与array_flip():<?$skus[0] = "hello";$skus[1] = "world";$skus[2] = "sky";$skus[3] = "is";$skus[4] = "blue";$words = array(0,2,4);$result = array_intersect_key($skus, array_flip($words));&nbsp;$setOrder = array_values($result); // to re orderecho "<pre>";print_r($setOrder);?>结果:Array(&nbsp; &nbsp; [0] => hello&nbsp; &nbsp; [1] => sky&nbsp; &nbsp; [2] => blue)您还可以使用array_values()重置密钥顺序。

慕虎7371278

您可以使用for循环并检查索引是否$words存在于$skus:$skus = [&nbsp; &nbsp; "Hello",&nbsp; &nbsp; "world",&nbsp; &nbsp; "sky",&nbsp; &nbsp; "is",&nbsp; &nbsp; "blue",];$words = array(0,2,4);$result = [];for ($i = 0; $i < count($words); $i++) {&nbsp; &nbsp; if (isset($skus[$words[$i]])) {&nbsp; &nbsp; &nbsp; &nbsp; $result[$i] = $skus[$words[$i]];&nbsp; &nbsp; }}print_r($result);结果Array(&nbsp; &nbsp; [0] => Hello&nbsp; &nbsp; [1] => sky&nbsp; &nbsp; [2] => blue)
打开App,查看更多内容
随时随地看视频慕课网APP