CodeMonkey
CodeMonkey

Reputation: 12424

How to access a PHP array with keys of inner values

I got a PHP array which looks like that:

array(3) {
  [0] => array(3) {
    ["Row"] => string(1) "1"
    ["Col"] => string(1) "1"
    ["Value"] => string(4) "lbl1"
  }
  [1] => array(3) {
    ["Row"] => string(1) "2"
    ["Col"] => string(1) "1"
    ["Value"] => string(4) "lbl2"
  }
  [2] => array(3) {
    ["Row"] => string(1) "3"
    ["Col"] => string(1) "1"
    ["Value"] => string(4) "lbl3"
  }
}

I know that every pair "Row" and "Col" is different from the others. I can't change the way I'm creating the array.

Can I somehow access the array kinda like a hash table like this: arr[Row => 0][Col => 0] and get the value which is in Row 0 and Col 0?

Upvotes: 0

Views: 114

Answers (3)

tmt
tmt

Reputation: 8614

You can use array_walk to get the value:

<?php

$a = array(
  0 => array(
    "Row" => "1",
    "Col" => "1",
    "Value" => "A",
  ),
  1 => array(
    "Row" => "2",
    "Col" => "1",
    "Value" => "B",
  ),
  2 => array(
    "Row" => "3",
    "Col" => "1",
    "Value" => "C",
  )
);

$rowNeedle = 3;
$colNeedle = 1;
$result = null;

array_walk($a, function($row, $key) use($rowNeedle, $colNeedle, &$result) {
  if($row['Row'] == $rowNeedle && $row['Col'] == $colNeedle) $result = $row['Value'];
});

echo $result;

The code will return the last match in case the array contains more than one row with the same Row and Col value (though, as you said, that is not your case).

Upvotes: 0

D4V1D
D4V1D

Reputation: 5849

If I understand your question well, you would need to reformat you array in order to access it like so: $array[1][1] to get Value of lbl1.

Try this where $array is your initial Array.

<?php

$return = array();
foreach($array as $value)
    $return[$value['Row']][$value['Col']] = $value['Value'];    

var_dump($return[1][1]); // outputs "lbl1"

Upvotes: 1

Kevin Ohashi
Kevin Ohashi

Reputation: 58

Not sure why you need col and row as fields. Could you the key of the primary array as one? If it's a 2 dimensional array with just col/row, you should be able to create your array just use the keys properly.

$foo[1][1]="lbl1";

$foo[2][1]="lbl2";

$foo[3][1]="lbl3";

It's just as simple to access then, $foo[1][1] returns "lbl1"

Upvotes: 0

Related Questions