How could I get values from array in PHP?
I have a php array like this:
array(
[0] =>
array(
... 3 elements ... )
['cat'] =>
'FF'
...
['iPath'] =>
'http://www.xx.com/images'
...
['dispName'] =>
'Fast Food'
...
)
[1] =>
array(
... 3 elements ... )
['cat'] =>
'G&L'
...
['iPath'] =>
'http://www.xx.com/images'
...
['dispName'] =>
'Grocery & Liquor'
...
)
[2] =>
array(
... 3 elements ... )
['cat'] =>
'Gas'
...
['iPath'] =>
'http://www.xx.com/ima开发者_C百科ges'
...
['dispName'] =>
'Gas Stations'
...
)
)
I want to be able to get the values for: iPath and dispName when cat = XXX. For instance, when cat = 'G&L'.
thanks
ldj
A. I don't understand anything from your example code.
B. To get array values in PHP you can use both numeric key values and string key values. Any of the following is valid:
$arr[1][7][0]
$arr['key1'][2]
$arr['42'][42]
$arr['keyLevel1']['keyLevel2']
Also note that $arr[42]
will address the same element as $arr['42']
.
C. Here's some recommended reading: http://php.net/manual/en/language.types.array.php
A'. To find the keys for all the Gas
values in the array.
function findGasInArray($arr){
$results = Array();
foreach($arr as $key => $val){
if($val == 'Gas')
$results[] = Array($key);
if(is_array($val)){
foreach(findGasInArray($val) as $otherVal){
array_unshift($otherVal, $key);
$results[] = $otherVal;
}
}
}
return $results;
}
findAllGasInArray($myBigArray);
Use array_filter for this. Assuming your array is named $arr, then do this:
$indexes = array_filter(function($i) { return $arr[i]['cat'] == 'Gas'; }, array_keys($arr));
$array[2]['cat']
精彩评论