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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.