简体   繁体   中英

PHP Multidimensional mixed arrays

How Do I access the innermost array? the grade is giving me a

$data = array();
$data[0] = 78;
$data[1] = 34;
$data[2] = 87;
$student = array(0 => array(
        "Stdno" => "212",
        "name" => "Lorem Ipsum",
        "subject" => "Networking",
        "grade" => $data
    ),
    1 => array(
        "Stdno" => "212",
        "name" => "Jimmy Shu",
        "subject" => "Informatics",
        "grade" => $data
    ),
    2 => array(
        "Stdno" => "212",
        "name" => "Amet Dolor",
        "subject" => "Discrete Combinatorics",
        "grade" => $data
    )
);
foreach ($student as $key => $value) {
    foreach ($value as $key => $value) {
        echo "<b>{$key}</b>: {$value}";
        echo "<br />";
    }
    echo "<br />";
}

First of all, you should really not use $key and $value again (in fact, I thought foreach ($value as $key=>$value) didn't work).

Assuming you want to echo the $data element at the same position than in your $student array (ie echo $data[0] for $student[0] ), you should use the first key :

foreach ($student as $key => $value) {
    foreach ($value as $key2 => $value2) {
        echo "<b>{$key2}</b>: ";
        if ($key2 == 'grade')
            echo $value2[$key];
        else
            echo $value2;
        echo "<br />";
    }
    echo "<br />";
}

First, just a comment please avoid using same keys on foreach . like in your $value .

To fix your issue, it clearly says, it's an array but you try to echo it, you could try to use this instead.

echo "<b>{$key}</b>: " . json_encode($value);

As stated by @roberto06 you should avoid using same variables for cycles that are nested. Those variables will be overwriten by new values.

To the question: You could check wether $value is string or array

is_array($val) || is_string($val)

based on result you could write another foreach cycle or print string. in your second foreach you are foreaching this array:

array(
    "Stdno" => "212",
    "name" => "Lorem Ipsum",
    "subject" => "Networking",
    "grade" => $data
)

so the (second) $key will be "Stdno", "name", "subject", "grade" and values will be "212", "Lorem Ipsum", "Networking" (those are strings) and $data (this is array)

to print this array, you need to create new foreach and use it only when $key == "grade" or use implode on it:

 if($key == "grade"){
     $i = implode(', ', $value);
     //print or something
 }

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