PHP Is there any better way to create this new array?
for ($i = 0; $i < count($keyListArray); $i++) {
开发者_JS百科 $newArray[$i] = $myArray[$keyListArray[$i]];
}
//structure of arrays are as follows
//$keyListArray = array (1,4,5);
//$myArray = array(1=>array('hello', 4, 56, 7))
You're just trying to de-key $keyListArray
, right? Try
$newArray = array_values($keyListArray);
array_values()
returns all the values from the input array and indexes numerically the array. http://us2.php.net/manual/en/function.array-values.php
-- Edit for new info
You have some parenthesis mixed up with square brackets - that's what has confused everyone. You don't really need the $i to specify the keys since they will be consistent and numerical by default. The way you're doing it is fine, but a foreach will make things a bit shorter.
foreach ($keyListArray as $key) {
$newArray[] = $myArray[$key];
}
foreach($keyList as $key)
$newArray[] = $myArray[$key];
精彩评论