2016-04-25 128 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

相關問題