0

With the following array, how would I just print the last name?

Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.

$array = Array
(
    [0] => Array
        (
            [name] => FirstName
            [value] => John
        )

    [1] => Array
        (
            [name] => LastName
            [value] => Geoffrey
        )

    [2] => Array
        (
            [name] => MiddleName
            [value] => Smith
        )
)
George
  • 17
  • 1
  • 4

3 Answers3

1

I would normalize the array first:

$normalized = array();
foreach($array as $value) {
  $normalized[$value['name']] = $value['value'];
}

Then you can just to:

echo $normalized['LastName'];
dave
  • 62,300
  • 5
  • 72
  • 93
  • 1
    Nicely done. Is this a subtle hint that the original data set might be better off as a simple associative array instead of an indexed array containing a small associate arrays as data sets? – zipzit Jun 29 '14 at 23:30
  • This is the method I went for in the end. Thank you very much. – George Jul 01 '14 at 20:18
0

If you are not sure where the lastname lives, you could write a function to do this like this ...

function getValue($mykey, $myarray) {
    foreach($myarray as $a) {
        if($a['name'] == $mykey) {
            return $a['value'];
        }
    }
}

Then you could use

print getValue('LastName', $array);
bsoist
  • 775
  • 3
  • 10
0

This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:

 `foreach($array as $arr){
     (if $arr['name'] == "lastName") 
      print_r($arr['value']
  }` 
Maggz
  • 175
  • 9