简体   繁体   中英

Printing nested array

I am a newbie to this array thing as still learning. Need to print this nested array. Pls guide me how to do it as when trying to print it is not recognized.

$args = array(
        'pUserId'=>"veenu",
        "pPassword" => "somePass",
    "pCode" => 381,
    "pCity" => "DELHI",
        $pIn = array("TypeCode" => 22,"Subtype" => "21"));

The way I am trying to print is below

print_r($args[pIn] -> TypeCode);

Error when trying to print is "Undefined index: pIn" and "Trying to get property of non-object"

1.From what I see, you want to have a key pLn pointing to the nested array. This is how you do it:

"pIn" => array("TypeCode" => 22,"Subtype" => "21")

2.It's a good idea when using keys to enclose them in single quotes:

 print_r($args['pIn']['TypeCode']);

Cheers!

It should be

echo $args[$pIn]['TypeCode'];

This is a multi-dimensional array.

It has a parent array and an array with key $pIn .

You are putting $pIn as a key, but it is not defined. But if you want to put just pIn (as string), you don't need to express it in a variable.

What you need is simply

$args = array(
        "pUserId" => "veenu",
        "pPassword" => "somePass",
        "pCode" => 381,
        "pCity" => "DELHI",
        "pIn" => array(
                "TypeCode" => 22,
                "Subtype" => "21")
         );

As $args is now a multidimensional array, you will be able to get the TypeCode like this:

echo $args["pIn"]["TypeCode"];

As you have it written, you are assigning an array to the variable $pIn and including it in $args but not as an index. Your array as defined looks like:

array(5) {
  ["pUserId"]=>
  string(5) "veenu"
  ["pPassword"]=>
  string(8) "somePass"
  ["pCode"]=>
  int(381)
  ["pCity"]=>
  string(5) "DELHI"
  [0]=>
  array(2) {
    ["TypeCode"]=>
    int(22)
    ["Subtype"]=>
    string(2) "21"
  }
}

You probably want:

$args = array(
        'pUserId'=>"veenu",
        "pPassword" => "somePass",
    "pCode" => 381,
    "pCity" => "DELHI",
    "pIn" => array("TypeCode" => 22,"Subtype" => "21"));

    print_r($args["pIn"]["TypeCode"]);  

Notice how the print_r accesses the element you want.

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