从名为$words的数组中,我只想获得那些从数组$indexes获得索引的单词。 我得到的全部:
public function createNewWordsList($indexes) { $words = $this->wordsArray(); $licznik = 0; $result = array(); foreach($words AS $i => $word) { if($i == $indexes[$licznik]) { $licznik++; $result[] = $word; } } print_r($word); }但它不起作用。 我怎么解决这个问题?
From the array named $words I would like to get only those words that got indexes from array $indexes. All I got:
public function createNewWordsList($indexes) { $words = $this->wordsArray(); $licznik = 0; $result = array(); foreach($words AS $i => $word) { if($i == $indexes[$licznik]) { $licznik++; $result[] = $word; } } print_r($word); }but it don't work. How can I solve this?
最满意答案
看来你在错误的数组上进行迭代。 如果indexes包含您要保留的$words (以及它们的关联值),那么代码应该是:
public function createNewWordsList(array $indexes) { $words = $this->wordsArray(); $result = array(); // Iterate over the list of keys (indexes) to copy into $result foreach ($indexes as $key) { // Copy the (key, value) into $result only if the key exists in $words if (array_key_exists($key, $words)) { $result[$key] = $words[$key]; } } return $result; }如果您不需要原始键(索引)到返回的数组中,您可以通过使用$result[] = $words[$key];将值添加到$result来更改上面的代码$result[] = $words[$key]; 或者在使用return array_values($result);返回$result之前丢弃键return array_values($result); 。
It seems you iterate over the wrong array. If indexes contains the keys you want to keep from $words (together with their associated values) then the code should be like:
public function createNewWordsList(array $indexes) { $words = $this->wordsArray(); $result = array(); // Iterate over the list of keys (indexes) to copy into $result foreach ($indexes as $key) { // Copy the (key, value) into $result only if the key exists in $words if (array_key_exists($key, $words)) { $result[$key] = $words[$key]; } } return $result; }If you don't need the original keys (indexes) into the returned array you can change the code above by either add the values into $result using $result[] = $words[$key]; or discard the keys before returning $result using return array_values($result);.
更多推荐
发布评论