Quantcast
Channel: PHP Freaks: PHP Help
Viewing all articles
Browse latest Browse all 13200

Action for every key and value pair in multidimensional associative array of variable dimensions

$
0
0

Hi there,

 

I've posted this at stackoverflow but did not receive any replies so far so I'd like to try here as well.

------

I have an array of variable dimensions and namings. Sometimes associative, sometimes partially. Sometimes just a single array, sometimes multiple dimensions. An example array is this:

array(4) {
["name"]=>
string(9) "Some Name"
["user"]=>
array(2) {
["id"]=>
int(1)
["msgs"]=>
array(3) {
[0]=>
string(16) "My first message"
[1]=>
string(17) "My second message"
["folder"]=>
array(2) {
["first"]=>
string(13) "Some folder.."
[1]=>
string(17) "some other stuf.."
}
}
}
[0]=>
string(17) "More random stuff"
["foo"]=>
array(2) {
[0]=>
string(10) "more stuff"
["bar"]=>
string(7) "The end"
}
}

I would like to have a function that goes through every key and value pair and performs a function, without altering the structure of the array. In this case, I want to apply htmlspecialchars() with ENT_QUOTES on every key and value pair in the array while keeping the array itself intact structure wise.

I have tried with array_walk_recursive and array_map, neither seem to do the trick.

I'm pretty new to PHP but I tried the following function by messing about with how I think it should be done but it's obviously not working :)

  private function CreateErrorArray($array, $knownKeys=NULL) {
    if (is_array($array)) {
      foreach ($array as $key => $value) {
        if (is_array($value)) {
          if (is_null($knownKeys)) {  
            $keys = array($key);
            $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$key], $keys);
          } else {
            $keys = array_push($knownKeys, $key);
            $this->response['ERRORARRAY'][$key] = $this->CreateErrorArray($this->RequestClass->error[$knownKeys][$key], $keys);
          }
        } else {
          $this->response['ERRORARRAY'][$key] = $value;
        }
      }
    }
}

Viewing all articles
Browse latest Browse all 13200

Trending Articles