2016-04-25 130 views
0

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

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

回答

0

看来你迭代错阵列上。如果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之前丢弃密钥来更改上面的代码。

0

尝试:

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

这检查数组中的值,而不是OP正在请求的索引。 – Daan

相关问题