简体   繁体   中英

How to access PHP Associative Array with unkonwn Associative names

My PHP Array (example, Print_r dump)

Array
(
    [0] => Array
        (
            [Nick] => Bobby
            [FullName] => Bob Smith
        )

    [1] => Array
        (
            [Nick] => Mikey
            [FullName] => Mike Smithers
        )

)

If I don't know the values "Nick" or "FullName" how can I access the values in them.

The array will have two values and I was looking to understand how to get access to them if I don't know the name of it.

I would like it to print out (for example)

Output example trying to get to: "Value one is Bobbie value two is Bob Smith "

but I don't know [Nick] or [FullName] how would one access "Bobbie" or "Bob Smith" (Array being passed in)

Thanks.

foreach ($my_arr as $key => $value) {
    list( $value_one, $value_two) = $value;
    echo "Value one is $value_one value two is $value_two\n";
}

If you just want to get the values, you can do:

$values = array_values($my_arr);

$values[0]; // the first value
$values[1]; // the second value
foreach($list as $array) { 
    foreach($array as $key => $value) {
        echo "The value of {$key} is: {$value}";
    }
}

here are two examples for handle ....

 <?php 
     $array = array(array("Bobbie"=>"Bobb",
                          "BobS"=>"BobbS"),
                    array("Foo"=>"Bar",
                          "Hello"=>"World")
              );

        // Method No.1
        foreach($array as $arr) {
           foreach($arr as $key=>$val) {
             echo $key."\n";
           }
        }
        // Method No.2
        // you can use the function array_keys() to get the key-names
        foreach($array as $arr) {

        $keys = array_keys($arr);
        echo "<h1>Keys:</h1><pre>".print_r($keys,1)."</pre>";
     }
 ?>

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