Skip to main content

How do I pick only the first few items in an array?


Here's something simple for someone to answer for me. I've tried searching but I don't know what I'm looking for really.



I have an array from a JSON string, in PHP, of cast and crew members for a movie.



Here I am pulling out only the people with the job name 'Actor'




foreach ($movies[0]->cast as $cast) {
if ($cast->job == 'Actor') {
echo '<p><a href="people.php?id=' . $cast->id . '">' . $cast->name . ' - ' . $cast->character . '</a></p>';
}
}



The problem is, I would like to be able to limit how many people with the job name 'Actor' are pulled out. Say, the first 3.



So how would I pick only the first 3 of these people from this array?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. Use a variable called $num_actors to track how many you've already counted, and break out of the loop once you get to 3.

    $num_actors = 0;
    foreach ( $movies[0]->cast as $cast ) {
    if ( $cast->job == 'Actor' ) {
    echo '...';

    $num_actors += 1;
    if ( $num_actors == 3 )
    break;
    }
    }

    ReplyDelete
  2. OK - this is a bit of over-kill for this problem, but perhaps it serves some educational purposes. PHP comes with a set of iterators that may be used to abstract iteration over a given set of items.

    class ActorIterator extends FilterIterator {
    public function accept() {
    return $this->current()->job == 'Actor';
    }
    }

    $maxCount = 3;
    $actors = new LimitIterator(
    new ActorIterator(
    new ArrayIterator($movies[0]->cast)
    ),
    0,
    $maxCount
    );
    foreach ($actors as $actor) {
    echo /*... */;
    }


    By extending the abstract class FilterIterator we are able to define a filter that returns only the actors from the given list. LimitIterator allows you to limit the iteration to a given set and the ArrayIterator is a simple helper to make native arrays compatible with the Iterator interface. Iterators allow the developer to build chains that define the iteration process which makes them extremely flexible and powerful.

    As I said in the introduction: the given problem can be solved easily without this Iterator stuff, but it provides the developer with some extended options and enables code-reuse. You could, for example, enhance the ActorIterator to some CastIterator that allows you to pass the cast type to filter for in the constructor.

    ReplyDelete
  3. $actors=array_filter($movies[0]->cast, function ($v) {
    return $v->job == 'Actor';
    });

    $first3=array_slice($actors, 0, 3);


    or even

    $limit=3;
    $actors=array_filter($movies[0]->cast, function ($v) use (&$limit) {
    if ($limit>0 && $v->job == 'Actor') {
    $limit--;
    return true;
    }
    return false;
    });

    ReplyDelete
  4. Add a counter and an if statement.

    $count = 0;
    foreach ($movies[0]->cast as $cast)
    {
    if ($cast->job == 'Actor')
    {
    echo '<p><a href="people.php?id=' . $cast->id . '">' . $cast->name . ' - ' . $cast-character . '</a></p>';

    if($count++ >= 3)
    break;
    }
    }

    ReplyDelete
  5. $limit = 3;
    $count = 0;

    foreach ($movies[0]->cast as $cast) {
    // You can move the code up here if all you're getting is Actors
    if ($cast->job == 'Actor') {
    if ($count == $limit) break;// stop the loop
    if ($count == $limit) continue;// OR move to next item in loop
    $count++;
    echo '<p><a href="people.php?id='
    . $cast->id
    . '">'
    . $cast->name
    . ' - '
    . $cast->character
    . '</a></p>';
    }
    }

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex