Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Iterating key/value pairs #12

Open
oasis9 opened this issue Oct 13, 2018 · 1 comment
Open

Iterating key/value pairs #12

oasis9 opened this issue Oct 13, 2018 · 1 comment

Comments

@oasis9
Copy link

oasis9 commented Oct 13, 2018

Not sure how to do this per the current implementation.
each() only takes one parameter, the value. The key could always be the index in the event that special keys are not used.

@jodiedunlop
Copy link
Contributor

Currently each() works only on a collection. This means that if you call each() on an item (eg. a node containing an associative array or some primitive value) then it will wrap the item in a collection, so that each() receives the item.

To iterate key/value pairs would require a breaking change to the API that each() would not wrap an associative array or an iterable object, and then it could therefore receive $key as it's second argument - when called on a collection, this would be the sequential array index.

I think this would be a good change though, and it could coincide with implementing collection() and item():

// alternative to get() to force the type of node expected.
$arrayobj->collection('books.0'); // If referencing an item, automatically wrap in a collection
$arrayobj->item('books'); // If referencing a collection, automatically call first() to get the first item

// revised each()
$arrayobj->item('books')->each(function($val, $key) {
   echo "$key: $val\n";   // eg.  title: 1984
});
$arrayobj->collection('books.0')->each(function($book, $index) {
  echo "$index: {$book->title}\n"; // eg. 0: 1984
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants