Anahkiasen / underscore-php

A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel
http://anahkiasen.github.com/underscore-php/
1.12k stars 88 forks source link

Find element in nested array by child key-value? #24

Open epicwhale opened 10 years ago

epicwhale commented 10 years ago

If I have an array of arrays (or objects). How do I find a child element which matches a particular key value?

For example

[
  [
     name => 'john',
     age => 17
  ],
  [
     name => 'jane',
     age => 22
  ]
]

Is there a way I can do an array find where 'name=john' so I get the index 0 as the result? or whatever are the matching indices.

epicwhale commented 10 years ago

@Anahkiasen Is there an implementation for this which I am overlooking?

Anahkiasen commented 10 years ago

Hm you can get the matching object with a basic Arrays::filters but I don't think we have any method to get the matching key, unless you do an array_search with the object afterwards.

epicwhale commented 10 years ago

Implementing support for this would be very useful. Something exactly along the lines of Underscore js' where and findWhere implementations - http://underscorejs.org/#where

Anahkiasen commented 10 years ago

Well if you want to send a PR I'l gladly accept it, otherwise you'll have to wait for a bit until I can have some time to take a look at that.

epicwhale commented 10 years ago

@Anahkiasen if you can drop me the specs as to what exactly would you want the function to be named, parameters, format, etc.. I'll try my best to find time on this

Anahkiasen commented 10 years ago

Well I actually don't have anything in mind, the only requirement is for the array to be the first argument but otherwise, since you're the one that was looking for it, you're best suited as for the method name. You can use the JS version's name if you think that'll help other people with the same needs find it faster.