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
)
)
-
1Your array structure seems overly complicated. Is the last name always in the second spot?bsoist– bsoist2014年06月29日 18:51:47 +00:00Commented Jun 29, 2014 at 18:51
-
I cannot change the array, it's from an external source.George– George2014年06月29日 18:53:15 +00:00Commented Jun 29, 2014 at 18:53
-
Duplicate. already answered here stackoverflow.com/questions/6661530/…Onimusha– Onimusha2014年06月29日 18:58:46 +00:00Commented Jun 29, 2014 at 18:58
3 Answers 3
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'];
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);
Comments
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']
}`