phew phew - 5 months ago 10
PHP Question

nested foreach() get a proper result

I have simple nested

foreach()
but I do not get what I thought it will.

here is the full code:

public function namelist() {
return array('lastname', 'firstname', 'middlename');
}

public function nameRequest($namelist) { // either lastname, firstname or middlename
switch($namelist) {
case 'lastname':
$request = array('ramirez', 'corazon', 'gonzaga');
break;
case 'firstname':
$request = array('michael', 'michaela', 'angel');
break;
case 'middlename':
$request = array('osaka', 'oscar', 'roxas');
break;
}
return $request;
}


I want a result like this:

Lastname: ramirez, corazon, gonzaga
Firstname: michael, michaela, angel
Middlename: osaka, oscar, roxas


But when I tried to code it like this:

public function fullname() {
$namelist = '';
$namedata = '';
$namelists = self::namelist();

foreach ($namelists as $names) {
$namelist .= $names . ': ';
$namerequest = self::nameRequest($names);

foreach ($namerequest as $namerequests){
$namedata .= $namerequests . ',';
}
}
return $namelist . ': ' . $namedata;
}


it returns:

lastname: firstname: middlename: ramirez, corazon, gonzaga, michael, michaela, angel, osaka, oscar, roxas


So how can I solved this ?

Answer

There are some misplaced statements:

<pre>
<?php
function namelist() {
    return array('lastname', 'firstname', 'middlename');
}
function nameRequest($namelist) { // either lastname, firstname or middlename
    switch($namelist) {
        case 'lastname':
        $request = array('ramirez', 'corazon', 'gonzaga');
        break;
        case 'firstname':
        $request = array('michael', 'michaela', 'angel');
        break;
        case 'middlename':
        $request = array('osaka', 'oscar', 'roxas');
        break;
    }
    return $request;
}
function fullname() {
    $namelist = '';
    $namelists = namelist();
    foreach ($namelists as $names) {
        $namedata = ''; // moved
        $namerequest = nameRequest($names);
        foreach ($namerequest as $namerequests){
            $namedata .= $namerequests . ',';
        }
        $namelist .= $names . ': ' . $namedata . "\n"; // new
    }
    return $namelist; // modified
}
echo fullname();
?>

Note: I removed the object orientation for my test.
Test: http://phpfiddle.org/main/code/v82x-czc4

Also consider using implode() instead of your inner foreach. It is shorter and will solve the trailing , issue you still have.