Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize this array loop

Tags:

arrays

php

I have array which contains info about many flights. I want only the five lowest prices.

First I make a loop to sort array by price.

Second I print first five array

But it takes more time..How can I reduce this time?

foreach ($flights_result->json_data['response']['itineraries'] as $key => $value)
{
    $mid[$key] = $value['price']['totalAmount'];
}

//Sort the data with mid descending
//Add $data as the last parameter, to sort by the common key
array_multisort($mid, SORT_ASC, $flights_result->json_data['response']['itineraries']);

// print 5 arrays
foreach ($flights_result->json_data['response']['itineraries'] as  $value)
{
    echo 'departureTime:' . $value['inboundInfo']['departureTime'] . '</br>';
    echo 'layoverInMin:' . $value['inboundInfo']['layoverInMin'] . '</br>';
    //      // loop echo 

    foreach ($value['inboundInfo']['flightNumbers'] as $flightNumbers)
    {
        echo 'flightNumbers  :' . $flightNumbers . '</br>';
    }

    echo 'durationInMin:' . $value['inboundInfo']['durationInMin'] . '</br>';
    echo 'localDepartureTimeStr:' . $value['inboundInfo']['localDepartureTimeStr'] . '</br>';
    echo ' arrivalTime:' . $value['inboundInfo']['arrivalTime'] . '</br>';
    echo ' numStops:' . $value['inboundInfo']['numStops'] . '</br>';

    ////     loop 
    foreach ($value[' inboundInfo']['flightClasses'] as $flightClasses)
    {
        echo 'flightClasses name :' . $flightClasses['name'] . '</br>';
        echo 'flightClasses fareClass :' . $flightClasses['fareClass'] . '</br>';
    }

    echo 'localArrivalTimeStr:' . $value['inboundInfo']['localArrivalTimeStr'] . '</br>';
    //      loop  echo

    foreach ($value[' carrier'] as $carrier)
    {
        echo 'carrier name :' . $carrier['name'] . '</br>';
        echo 'carrier code :' . $carrier['code'] . '</br>';
    }

    echo 'amount:' . $value['price']['amount'] . '</br>';
    echo ' totalAmount :' . $value['price']['totalAmount'] . '</br>';
    echo 'pricePerPassenger:' . $value['price']['pricePerPassenger'] . '</br>';
    echo 'currencyCode: ' . $value['price']['currencyCode'] . '</br>';
    echo 'totalPricePerPassenger: ' . $value['price']['totalPricePerPassenger'] . '</br>';
    echo 'includesTax: ' . $value['price ']['includesTax'] . '</br>';
    echo 'destinationCountryCode:' . $value[' destinationCountryCode'] . ' </br> -------- </br>';

    $count++;
    if ($count > 2)
    {
        break;
    }
}

array example

Array
(
    [0] => Array
        (
            [ecpcRank] => 0
            [inboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1381448400000
                    [layoverInMin] => 1359
                    [flightNumbers] => Array
                        (
                            [0] => DL3672
                            [1] => EK204
                            [2] => EK923
                        )

                    [durationInMin] => 2360
                    [airportsExpanded] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => JFK
                            [3] => DXB
                            [4] => DXB
                            [5] => CAI
                        )

                    [localDepartureTimeStr] => 2013/10/10 18:40 -0500
                    [airports] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => DXB
                            [3] => CAI
                        )

                    [arrivalTime] => 1381590000000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/12 17:00 +0200
                )

            [location] => Array
                (
                    [0] => Array
                        (
                            [code] => CAI
                            [name] => Cairo
                        )

                    [1] => Array
                        (
                            [code] => DXB
                            [name] => Dubai
                        )

                    [2] => Array
                        (
                            [code] => PHL
                            [name] => Philadelphia
                        )

                    [3] => Array
                        (
                            [code] => JFK
                            [name] => New York J F Kennedy
                        )

                    [4] => Array
                        (
                            [code] => MXP
                            [name] => Milan Malpensa
                        )

                )

            [carrier] => Array
                (
                    [0] => Array
                        (
                            [name] => Delta Air Lines
                            [code] => DL
                        )

                    [1] => Array
                        (
                            [name] => US Airways
                            [code] => US
                        )

                    [2] => Array
                        (
                            [name] => Emirates
                            [code] => EK
                        )

                    [3] => Array
                        (
                            [name] => Egyptair
                            [code] => MS
                        )

                )

            [bookingType] => WEBSITE
            [price] => Array
                (
                    [name] => 
                    [nameOTA] => 
                    [description] => 
                    [amount] => 26280
                    [totalAmount] => 26280
                    [pricePerPassenger] => 26280
                    [currencyCode] => EGP
                    [totalPricePerPassenger] => 26280
                    [includesTax] => 1
                )

            [generatedDate] => 1380212804686
            [providerId] => emirates.com
            [id] => MS703[CAI-MXP],EK205[MXP-JFK],US3407[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI]
            [originCountryCode] => EG
            [bookingCode] => 13600077136293253
            [destinationCountryCode] => US
            [outboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1380958800000
                    [layoverInMin] => 1050
                    [flightNumbers] => Array
                        (
                            [0] => MS703
                            [1] => EK205
                            [2] => US3407
                        )

                    [durationInMin] => 1940
                    [airportsExpanded] => Array
                        (
                            [0] => CAI
                            [1] => MXP
                            [2] => MXP
                            [3] => JFK
                            [4] => JFK
                            [5] => PHL
                        )

                    [localDepartureTimeStr] => 2013/10/05 09:40 +0200
                    [airports] => Array
                        (
                            [0] => CAI
                            [1] => MXP
                            [2] => JFK
                            [3] => PHL
                        )

                    [arrivalTime] => 1381075200000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/06 11:00 -0500
                )

        )

    [1] => Array
        (
            [ecpcRank] => 0
            [inboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1381448400000
                    [layoverInMin] => 1359
                    [flightNumbers] => Array
                        (
                            [0] => DL3672
                            [1] => EK204
                            [2] => EK923
                        )

                    [durationInMin] => 2360
                    [airportsExpanded] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => JFK
                            [3] => DXB
                            [4] => DXB
                            [5] => CAI
                        )

                    [localDepartureTimeStr] => 2013/10/10 18:40 -0500
                    [airports] => Array
                        (
                            [0] => PHL
                            [1] => JFK
                            [2] => DXB
                            [3] => CAI
                        )

                    [arrivalTime] => 1381590000000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/12 17:00 +0200
                )

            [location] => Array
                (
                    [0] => Array
                        (
                            [code] => CAI
                            [name] => Cairo
                        )

                    [1] => Array
                        (
                            [code] => PHL
                            [name] => Philadelphia
                        )

                    [2] => Array
                        (
                            [code] => DXB
                            [name] => Dubai
                        )

                    [3] => Array
                        (
                            [code] => JFK
                            [name] => New York J F Kennedy
                        )

                )

            [carrier] => Array
                (
                    [0] => Array
                        (
                            [name] => Delta Air Lines
                            [code] => DL
                        )

                    [1] => Array
                        (
                            [name] => Emirates
                            [code] => EK
                        )

                )

            [bookingType] => WEBSITE
            [price] => Array
                (
                    [name] => 
                    [nameOTA] => 
                    [description] => 
                    [amount] => 28183
                    [totalAmount] => 28183
                    [pricePerPassenger] => 28183
                    [currencyCode] => EGP
                    [totalPricePerPassenger] => 28183
                    [includesTax] => 1
                )

            [generatedDate] => 1380212804689
            [providerId] => emirates.com
            [id] => EK928[CAI-DXB],EK203[DXB-JFK],DL6122[JFK-PHL]|DL3672[PHL-JFK],EK204[JFK-DXB],EK923[DXB-CAI]
            [originCountryCode] => EG
            [bookingCode] => 13600077139546083
            [destinationCountryCode] => US
            [outboundInfo] => Array
                (
                    [aircraftTypes] => Array
                        (
                        )

                    [departureTime] => 1380966900000
                    [layoverInMin] => 947
                    [flightNumbers] => Array
                        (
                            [0] => EK928
                            [1] => EK203
                            [2] => DL6122
                        )

                    [durationInMin] => 2118
                    [airportsExpanded] => Array
                        (
                            [0] => CAI
                            [1] => DXB
                            [2] => DXB
                            [3] => JFK
                            [4] => JFK
                            [5] => PHL
                        )

                    [localDepartureTimeStr] => 2013/10/05 11:55 +0200
                    [airports] => Array
                        (
                            [0] => CAI
                            [1] => DXB
                            [2] => JFK
                            [3] => PHL
                        )

                    [arrivalTime] => 1381093980000
                    [numStops] => 2
                    [flightClasses] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [1] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                            [2] => Array
                                (
                                    [name] => Economy
                                    [fareClass] => 1
                                )

                        )

                    [localArrivalTimeStr] => 2013/10/06 16:13 -0500
                )

        )

)

like image 448
user1080247 Avatar asked Sep 26 '13 16:09

user1080247


People also ask

How do you optimize a loop in Python?

We can optimize loops by vectorizing operations. This is one/two orders of magnitude faster than their pure Python equivalents (especially in numerical computations). Vectorization is something we can get with NumPy. Numpy is a library with efficient data structures designed to hold matrix data.


3 Answers

To answer your questions:

but it take more time..how to reduce this big time?

Before you can reduce that you need to find out exactly where that more comes from. As you wrote in a comment, you are using a remote request to obtain the data.

Sorting for array the data you've provided works extremely fast, so I would assume you don't need to optimize the array sorting but just the way when and how you get the data from remote. One way to do so is to cache that or to prefetch it or to do parallel processing. But the details so far are not important at all, unless you've found out where that more comes from so that it is clear what is responsible for big time so then it can be looked into reducing it.

Hope this is helpful so far, and feel free to add the missing information to your question.

You can see the array-only code in action here, it's really fast:

  • https://eval.in/51770

You can find the execution stats just below the output, exemplary from there:

OK (0.008 sec real, 0.006 sec wall, 14 MB, 99 syscalls)

like image 162
hakre Avatar answered Sep 24 '22 06:09

hakre


You should really install a profiler (XHProf) and check what exactly takes so much time.

I assume it is the sorting, because foreach through the final array of 5 elements should be lighning fast. Why do you sort it then? If the sole purpose of sorting is to find 5 "lowest" items, then the fastest way would be to just find 5 lowest items:

$min5 = array();
foreach ($flights_result->json_data['response']['itineraries'] as $key => $value)
{
    $amount = $value['price']['totalAmount'];

    // Just put first 5 elements in our result array
    if(count($min5) < 5) {
        $min5[$key] = $amount;
        continue;
    }
    // Find largest element of those 5 we check
    $maxMinK = null;
    foreach($min5 as $minK=>$minV) {
        if($maxMinK === null) {
            $maxMinK = $minK;
            continue;
        }
        if($minV > $min5[$maxMinK])
        {
            $maxMinK = $minK;
        }
    }
    // If our current amount is less than largest one found so far,
    // we should remove the largest one and store the current amount instead
    if($amount < $min5[$maxMinK])
    {
        unset($min5[$maxMinK]);
        $min5[$key] = $amount;
    }
}
asort($min5); // now we can happily sort just those 5 lowest elements

It will find 5 items with about O(6n) which in your case should better than potential O(n²) with sorting; Then you may just use it like:

foreach($min5 as $key=>$minValue)
{
    $intinerary = $flights_result->json_data['response']['itineraries'][$key]
    ...
}

This should be a lot faster, provided it was the sorting! so get that XHprof and check :)

like image 37
Adam Zielinski Avatar answered Sep 23 '22 06:09

Adam Zielinski


Here's what I would have done:

<?php

    // Initialize html Array
    $html = array();

    // Iterate Over Values, Using Key as Label.
    foreach( $value['inboundInfo'] as $inboundLabel => &$inboundValue )
    {
        // Check for Special Cases While Adding to html Array
        if( $inboundLabel == 'flightNumbers' )
        {
            $html[] = $inboundLabel . ': ' . implode( ', ', $inboundValue );
        }
        elseif( $inboundLabel == 'flightClasses' )
        {
            foreach( $inboundValue as $fcName => &$fcValue )
            {
                $html[] = 'flightClasses ' . $fcName . ': ' . $fcValue;
            }
        }
        else
        {
            $html[] = $inboundLabel . ': ' . $inboundValue;
        }
    }

    // Don't Need Foreach to Complicate Things Here
    $html[] = 'carrier name: ' . $value[' carrier']['name'];
    $html[] = 'carrier code: ' . $value[' carrier']['code'];

    // Add Price Info to Array
    foreach( $value['price'] as $priceLabel => &$price )
    {
        $html[] = $priceLabel . ': ' . $price;
    }
    $html[] = ' -------- </br>';

    // And Finally:
    echo implode( "<br/>\r\n", $html );

It's either that or write a recursive function to go through all the data. Also note, this only works if your data is in the order you want.

like image 31
Jason Avatar answered Sep 23 '22 06:09

Jason