简体   繁体   中英

How can I sort this array alphabetically using php and use foreach to loop through it

I have this data in an array stored as $eventTitles . I am trying to sort it alphabetically.

Array (
    [Customer Challenge - Sustainability] => Customer Challenge - Sustainability
    [Manifesto Stores] => Manifesto Stores
    [Helpful Heroes] => Helpful Heroes
    [Ben 5 places left test] => Ben 5 places left test
    [Ben sold out test] => Ben sold out test
    [Ben 1 space left test] => Ben 1 space left test
    [Follow the Product] => Follow the Product
    [Living the Operating Model] => Living the Operating Model
    [Leaders Unplugged] => Leaders Unplugged
    [Market Trends] => Market Trends
    [FINAL MASTER EVENT CONFIG - DO NOT AMEND] => FINAL MASTER EVENT CONFIG - DO NOT AMEND
    [You Can Do It] => You Can Do It
    [Customer Challenge - Communicating EDLP] => Customer Challenge - Communicating EDLP
) 

Using:

$eventTitles = ksort($eventTitles);

foreach($eventTitles as $title) {
    $t = urlencode($title);
    //if statement to check if the title is in the url param 
    //and if it is we can put selected in the left hand nav as a class
    if($_GET["title"] == $title ) {
        $selected = ' class="selected"';
    } else {
        $selected = ' ';
    }
    $rtnStr .= '<li><a'.$selected.'href="list.php?title='.urlencode($title).
                       '" data-value="'.$title.'">'.$title.'</a></li>';
}

produces the following error when I try to loop through the titles and render them each out:

Warning: Invalid argument supplied for foreach() in model.php on line 281

Any clues on what is going wrong would me much appreciated.

ksort takes an array reference and returns a boolean ( true or false ).

When you do $eventTitles = ksort($eventTitles); you are overwriting $eventTitles to a boolean which replaces the array.

Just do:

ksort($eventTitles);

DOCs on ksort(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM