Jump to content

[SOLVED] PHP foreach () loop through two dimentional array


Arbiter

Recommended Posts

I'm pretty new to PHP and I've been at this for days now. I'm trying to loop through a two dimentional array formed by parse_ini_file() and if a certain item is found in a certain section, return the value of that item. The code i've come up with results in my first if statement never being true and I can't figure out why. Here's my code:

 

function get_value_of($section,$item)
{
  $ini_array = parse_ini_file("IDLE_names.ini", true);
  //print_r($ini_array);
  foreach ($ini_array as $i)
  {
    if ($i == $section)
    {
      foreach ($i as $x)
      {
        if ($x == $item) { return "$x"; }
      }
    }
  }
}

 

The array formed by parse_ini_file() comes out like:

Array
(
    [Arbiter] => Array
        (
            [account] => Arbiter
            [password] => 3f2859a7277ec1f2a1ad6743884bb73f
            [class] => kewl kid

 

Etc..my function is being called like: get_value_of("$player","class");

and $player is set by:  $player = $_GET['player'];

 

any help would be much appreciated, I just really want to finish this bit of code.

 

since parse_ini_file produces an associative array (like this key => value) you have to change foreach loop accordingly to be like:

 

function get_value_of($section,$item)
{
  $ini_array = parse_ini_file("IDLE_names.ini", true);
  //print_r($ini_array);
  foreach ($ini_array as $key => $value)
  {
    if ($value == $section)
    {
      foreach ($value as $xkey => $xvalue)
      {
        if ($xkey == $item) { return "$xvalue"; }
      }
    }
  }
}

 

This function might not work properly but you get the idea

Why not just do :

 

function get_value_of($section,$item)
  {
  $ini_array = parse_ini_file("filename.ini", true);
  result:=$ini_array[$section][$item];
  }

 

Taking your example ini array the function call get_value_of($player,'class') with $player='Arbiter' would return $ini_array['Arbiter']['class'] which equals 'kewl kid'

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.