19592

PHP array_filter with argument to callback [duplicate]

Question:

This question already has an answer here:

<ul><li> <a href="/questions/5482989/php-array-filter-with-arguments" dir="ltr" rel="nofollow">PHP array_filter with arguments</a> <span class="question-originals-answer-count"> 6 answers </span> </li> <li> <a href="/questions/2529728/is-it-possible-if-callback-in-array-filter-receive-parameter" dir="ltr" rel="nofollow">is it possible if callback in array_filter receive parameter?</a> <span class="question-originals-answer-count"> 5 answers </span> </li> </ul>

I need to filter an array in PHP but am not sure how to pass an argument to the callback. Essentially I have 2 comparisons to make on each item in the array.

// This data will be sent to the function as JSON so I'm "creating" the JSON here. $data = json_encode(Array( Array("StartDate"=>"2014/07/31","LocZipCode"=>"19406","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/08/31","LocZipCode"=>"23513","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/07/31","LocZipCode"=>"92108","LocationURL"=>"BU","EventType"=>"UN"), Array("StartDate"=>"2014/09/30","LocZipCode"=>"78661","LocationURL"=>"BU","EventType"=>"UN") )); // even using a global variable doesn't // make it visible in getUniv() function global $univ_seg; $univ_seg = 'FSU'; getUA($data, $univ_seg); function getUniv($var){ return($var["EventType"] == "UN" && $var["LocationURL"] == $univ_seg); } function getUA($data, $univ_seg) { $univ_sched = json_decode($data, true); $re = array_filter($univ_sched, "getUniv"); print_r($re); }

I've also tried using a lambda but I just can't make it work. Any ideas??

Answer1:

// even using a global variable doesn't // make it visible in getUniv() function global $univ_seg; $univ_seg = 'FSU';

That's not how globals work - to access a global variable, you need a matching global declaration in the each scope you want to use it in.

function getUniv($var){ global $univ_seg; return($var["EventType"] == "UN" && $var["LocationURL"] == $univ_seg); }

This would work better as an anonymous function, though:

$re = array_filter($univ_sched, function getUniv($var) use ($univ_seg) { return($var["EventType"] == "UN" && $var["LocationURL"] == $univ_seg); });

Answer2:

Why not try it with an anonymous function instead? I find callbacks work better with that

function getUA($data, $univ_seg) { $univ_sched = json_decode($data, true); $re = array_filter($univ_sched, function($var){ return($var["EventType"] == "UN" && $var["LocationURL"] == 'FSU'); }); print_r($re); }

Answer3:

I got it to work using an object, <a href="http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback" rel="nofollow">http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback</a>

class univFilter { public $univ_seg; public function filter($var) { if($var["EventType"] == "UN" && $var["LocationURL"] == $this->univ_seg) return true; else return false; } } $data = json_encode(Array( Array("StartDate"=>"2014/07/31","LocZipCode"=>"19406","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/08/31","LocZipCode"=>"23513","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/11/30","LocZipCode"=>"92108","LocationURL"=>"BU","EventType"=>"UN"), Array("StartDate"=>"2014/09/30","LocZipCode"=>"78661","LocationURL"=>"BU","EventType"=>"UN") )); $univ_seg = "BU"; getUA($data,$univ_seg); function getUA($data, $univ_seg) { $f = new univFilter(); $f->univ_seg = $univ_seg; $univ_sched = json_decode($data, true); $data = array_filter($univ_sched,array($f,"filter")); print_r($data); }

Answer4:

You could use a lambda function:

$data = json_encode(Array( Array("StartDate"=>"2014/07/31","LocZipCode"=>"19406","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/08/31","LocZipCode"=>"23513","LocationURL"=>"FSU","EventType"=>"UN"), Array("StartDate"=>"2014/07/31","LocZipCode"=>"92108","LocationURL"=>"BU","EventType"=>"UN"), Array("StartDate"=>"2014/09/30","LocZipCode"=>"78661","LocationURL"=>"BU","EventType"=>"UN") )); $univ_seg = 'FSU'; getUA($data, $univ_seg); function getUnivFunc($univ_seg){ return create_function('$a','return $a["EventType"] == "UN" && $a["LocationURL"] == "' . $univ_seg . '";'); } function getUA($data, $univ_seg) { $univ_sched = json_decode($data, true); $re = array_filter($univ_sched, getUnivFunc($univ_seg)); print_r($re); }

<a href="http://codepad.org/LnVVry5L" rel="nofollow">http://codepad.org/LnVVry5L</a>

Gives:

Array ( [0] => Array ( [StartDate] => 2014/07/31 [LocZipCode] => 19406 [LocationURL] => FSU [EventType] => UN ) [1] => Array ( [StartDate] => 2014/08/31 [LocZipCode] => 23513 [LocationURL] => FSU [EventType] => UN ) )

Recommend

  • Replicate elements from an array into a different array in Matlab
  • How can I parse a XML document retrieved from SRU?
  • Copying values of a numpy array into specific location of sparse matrix
  • C fscanf input validation
  • DESC command and key column within it
  • How can you/Is it feasible to override Doctrine_Connection in Symfony?
  • ZF2 + Doctrine 2 - Entity created when requirements not met and values empty
  • How to add some non-standard font to Html?
  • Exporting HTML/CSS with Inkspace or Gimp [closed]
  • Inner Join 3 tables
  • Specifying multiple one-to-many relationships between tables in Hibernate
  • C stat() ignoring files
  • USB data transfer to iPhone
  • Swift 3.0 Pin Color Annotation Not Changing in MapView
  • Why does calculation with OpenMP take 100x more time than with a single thread?
  • Unix shell script to search for error codes in thousand files then print the count in text file
  • Define name for column func.count in sqlalchemy
  • Error while uploading file to Amazon S3 bucket
  • Swagger/Swashbuckle list acceptable values?
  • Stored data can't access in Yii
  • Is there a MySQL query that can encode to JSON in exactly this way?
  • Java: List the dates between a start and end date [duplicate]
  • FCM on app closed
  • LINQ to NHibernate WHERE EXISTS IN
  • NServiceBus - NServiceBus.Host as publisher and WPF app as subscriber. How To?
  • SharePoint Designer 2010 - Determine if today's date is within x days of a start date column us
  • Can you build a truly RESTful service that takes many parameters?
  • Initializer list vs. initialization method
  • Control modification in presentation layer
  • Sails.js/waterline: Executing waterline queries in toJSON function of a model?
  • Fetching methods from BroadcastReceiver to update UI
  • Rearranging Cells in UITableView Bug & Saving Changes
  • json Serialization in asp
  • Benchmarking RAM performance - UWP and C#
  • Angular 2 constructor injection vs direct access
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?