简体   繁体   中英

Using Foreach to echo array in an array

I want to echo each persona included in the array $personas.

The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").

Any help is much appreciated :)

<?php
$personas = array(
        $persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
        $persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
    );


foreach ($personas as $persona ) {
    foreach ( $person as $inner_param => $inner_value ) {

    echo $param . ": " . $value . "<br>";
    
    }


  };
?>

Desired result:

Name: John | Age: 30 | Nationality: Spain |

Name: Mike | Age: 45 | Nationality: Peru |

I believe that I fixed it. Should it be as follows? Any better option?

foreach ($personas as $persona ) {

    echo "<br>";
    foreach ( $persona as $param => $value ) {

    echo $param . ": " . $value . " | ";
    
    }
};

Try this;

$personas = array(
    $persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
    $persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);

foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
  $text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}

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