从在第二个数组中获取索引的数组中获取值


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);
}

但它不起作用。我该如何解决这个问题?

您似乎迭代了错误的数组。如果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中或在使用 return array_values($result); 返回$result之前丢弃键来更改上面的代码。

尝试:

public function createNewWordsList($indexes)
{
    $words = $this->wordsArray();
    $licznik = 0;
    $result = array();
    foreach($words AS $i => $word)
    {
        if(in_array($word,$indexes)) //check using in_array
        {
            $licznik++;
            $result[] = $word;
        }
    }
    print_r($word);
}