doucheng2210
doucheng2210
2017-04-20 17:32

PHP:如何遍历多维数组并输出子数组而不是子数组的元素

Its my first question here, because I usually find what I am looking for, but here I am lost.

I created a multidimensional array the following way:

Here is the code - from Input to the push:

This is the input into the textarea:

VIE-CAI
HAV-VRA
JFK-SYD

Here I am fetching the data from the text area on click, after an enter a new element should be created with the string of destinations:

$textarea = $_POST['many_destinations'];
$textarea = str_replace(' ', '', $textarea);
$textarea = strtoupper($textarea);
$textarea =  preg_split("/(
|
|)/", $textarea);

Now I am "exploding" these strings to elements of an array. Storing them in the main array $textarea_new

 foreach($textarea as $row) {
      $routes = explode('-', $row);
      array_push($textarea_new, $routes);
  }

At the beginning of the whole click function I declared this array as:

$textarea_new = array();

so right now I would expect it to look like this:

$textarea_new = array
      (
      array("VIE","CAI"),
      array("HAV","VRA"),
      array("JFK","SYD")
      );

EDIT: from your comments I can assume that it doesnt look like this, because you didnt face any problems with the following loop:

Now I want to loop through each route (subarray) and output it, so that i can handle each subarray seperately.

One of the most suggested things I found on stackoverflowwas the following, but it gave me really strange results:

foreach ($textarea_new as $route) {
        if (is_array($route)){
            foreach($route as $destination){
                echo $destination." ";

            }
        } 
    }

The output for the function above is the following: VIE CAI HAV VRA JFK SYD VIE CAI HAV VRA JFK SYD VIE CAI HAV VRA JFK SYD

but it should actually just be:

VIE CAI HAV VRA JFK SYD

Please tell me if you need more info and especially if this is not the right way to do it. Thank you!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongxie3681 dongxie3681 3年前

    The only real preparation that seems necessary is to, first, set all letters to uppercase. Beyond that, just write a regex pattern that validates and extracts in one step, then you can loop the results.

    Code: (Demo) (Pattern Demo)

    $flightpaths = 'VIE-CAI
    hav-vra
    JFK-SYD';
    
    if (!preg_match_all('~^([A-Z]{3})-([A-Z]{3})$~m', strtoupper($flightpaths), $out, PREG_SET_ORDER)) {
        echo 'Invalid Entry';
    } else {
        foreach ($out as $row) {
            echo "Destination #1: {$row[1]}
    ";
            echo "Destination #2: {$row[2]}
    
    ";
        }
    }
    

    Output:

    Destination #1: VIE
    Destination #2: CAI
    
    Destination #1: HAV
    Destination #2: VRA
    
    Destination #1: JFK
    Destination #2: SYD
    
    点赞 评论 复制链接分享

相关推荐