简体   繁体   中英

php - how to loop through values of one specific key in an associative array?

I am new to php , I have an associative array like this

$arr['Joe'] = "test1";
$arr['Joe'] = "test2";
$arr['Joe'] = "test3";

how do I loop through all the values test1, test2, test3 of this specific key Joe ?

I tried this

foreach ($arr as $key => $value) {
    echo $value;
}

and this

foreach ($arr as $key => $value) {
    echo $arr [$key]['Joe'];
}

But nothing ! Please help me?

I think this is what you want:

<?php

$arr['Joe'][] = "test1";
$arr['Joe'][] = "test2";
$arr['Joe'][] = "test3";

foreach ($arr['Joe'] as $key => $value) {
    echo $value;
}
?>

By adding [] after ['Joe'] the values will be saved like this:

(
    [Joe] => Array
        (
            [0] => test1
            [1] => test2
            [2] => test3
        )

)

To hold multiple values in an associative array they each need to be unique. eg.

$arr['Joe1'] = "test1";
$arr['Joe2'] = "test2";
$arr['Joe3'] = "test3";

and then

foreach ($arr as $value) {
    echo $value;
}

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