Obtaining name of "father" array from "child"

时间:2016-04-21 22:26:16

标签: php multidimensional-array

I want to be able to name a "father" array from it's child, for the goal of writing all HTTP variables sent to the page, and written to a debug file. Assuming that I have this code (and that the page is called remotely):

$father = array ( getallheaders(), $_POST, $_GET );
$info = '';
foreach ( $father as $child ){
  $info .= ${"child"} . "\n";
  $info .= '--------------' . "\n";
  foreach ( $child as $key => $val ){
    $info .= $key . ' : ' . $val . "\n";
  }
  $info .= "\n\n";
}

//write $info to a debug file

What I'm hoping to achieve is the debug file containing the following information:

getallheaders()
--------------
Host : 1.2.3.4
Connection : keep-alive
// all other members of getallheaders() array

$_POST
--------------
// assuming that page was called via HTTP POST
INPUT1 : input one text
INPUT2 : input two text
// all other members of $_POST array

$_GET
--------------
// assuming that page was called via HTTP GET
INPUT10 : input ten text
INPUT11 : input eleven text
// all other members of $_GET array
...

and so on...

At the moment, I get all the info in the debug file that I want, but the "name" of the father array that I'm currently working on is just being displayed as Array : which makes total sense, but I can't work out how to get it's name and display it as a string value. This is the contents of the debug file:

Array
--------------
Host : 1.2.3.4
Connection : keep-alive
// all other members of getallheaders() array

Array
--------------
// assuming that page was called via HTTP POST
INPUT1 : input one text
INPUT2 : input two text
// all other members of $_POST array

Array
--------------
// assuming that page was called via HTTP GET
INPUT10 : input ten text
INPUT11 : input eleven text
// all other members of $_GET array
...

I know I can create an iterator within the child's inner loop, and then call $father[0], $father[1] and somehow convert the name of the array into a string, but I was hoping someone could direct me to a more "elegant" way of doing things?

1 个答案:

答案 0 :(得分:2)

Your array does not has any information about children. Set appropriate keys:

$father = array ( 'getallheaders' => getallheaders(), '$_POST' => $_POST, '$_GET' => $_GET );

Then change your foreach in this way:

foreach( $father as $childname => $child )
{
    $info .= "$childname\n";
    (...)
}