从第二个数组中得到索引的数组中获取值(getting values from array that got indexes in second array)

编程入门 行业动态 更新时间:2024-10-15 00:18:54
从第二个数组中得到索引的数组中获取值(getting values from array that got indexes in second array)

从名为$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);.

更多推荐

本文发布于:2023-08-04 22:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1423430.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   个数   索引   indexes   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!