2017-09-27 6 views
-1

配列内の特定の条件を満たすアイテムのみを表示しようとしています。現時点では、配列内のすべてを出力しています。 私がこれまで持っているもの:配列内に特定の基準を持つアイテムのみを表示する

$records = $d->get("FoundCount"); 
$result = array(); 
for($i = 1; $ <= $record; $i++){ 

// various array components 
$show_published = $d->field(show_published); //this is the variable from the DB that will determine if the item is shown on the page. Yes/no string. 

if($show_published == 'Yes'){ 
$results[] = new Result(//various array components, $show_published, //more things); 
} 

これは出力に'No'としてラベル付けされたものを含むすべてのアイテムを、と思われます。

どのような指針も素晴らしいでしょう。私は数ヶ月の間だけPHPを使用しています。

+3

例で任意の定数、変数、メソッド、オブジェクト、および構文エラーを使用すると、どういうことが分かりますか? –

+0

$ d-> fieldの代わりにforループで$ record-> fieldを試してください –

+0

私のコードの曖昧さを残して申し訳ありません。私は共有できない情報が含まれているので、代わりに一般的な用語を使用する必要があります。変数の多くは、ビジネス名と私的な情報を含んでいます。 –

答えて

0

composerに精通していて、PHPパッケージをインストール/使用する方法がわかりません。 あなたは、あなたのプロジェクトの依存関係としてilluminate/supportパッケージを追加することができますし、レコードをフィルタするためにそのCollectionを使用している場合 - の線に沿って何か:この後

use Illuminate\Support\Collection; 

$collection = new Collection($records); 

$outputArray = $collection->filter(function($object) { 

    return (string) $object->field('show_published') === 'Yes'; 

})->toArray(); 

https://laravel.com/docs/5.5/collections

を、$outputArrayのみが含まれていますshow_publishedフラグがYesに設定されているレコード。

はまた、あなたがほとんど同じようにPHPのネイティブ関数array_filterを使用することができます。

$outputArray = array_filter($records, function($object) { 

    return (string) $object->field('show_published') === 'Yes'; 

}); 

http://php.net/manual/en/function.array-filter.php

+0

'if'ループの代わりに' array_filter'を使用しますか? –

+0

はい - 条件を 'array_filter'の2番目の引数であるクロージャー(関数)の中に入れます。単にレコードをフィルタリングし、関数が真を返す限り、これらのレコードは' $ outputArray' –

0

をここで開始する文字列の基準に基づいてフィルタ処理された新しい配列を作成する方法の簡単な例です。文字 'b'で私はあなたの基準が何であるか分かりませんが、あなたは確かにこのアプローチを取ってあなたのニーズに合うように修正することができます。

//Original array of things that are un-filtered 
     $oldArray = array("Baseball", "Basketball", "Bear", "Salmon", "Swordfish"); 

//An empty filtered array that we will populate in the loop below, based on our criteria. 
     $filteredArray = array(); 

     foreach($oldArray as $arrayValue) { 
       //Our criteria is to only add strings to our 
       //filtered array that start with the letter 'B' 
      if($arrayValue[0] == "B") 
      { 
       array_push($filteredArray, $arrayValue); 
      } 
     } 
//Our filtered array will only display 
//our 3 string items that start with the character 'B' 
     print_r($filteredArray); 

希望します。そうでない場合は、お気軽にお問い合わせください。

関連する問題