简体   繁体   中英

PHP Loop through array for value

I have a multidimensional array that is being populated by a mysql query. I need to pull out a value and cannot figure out how to do it, I can only get the keys and not the actual value. The array is show below and I want to extract the "SERVICE" value using a loop so i can echo each one out

Here is the array:

array (
  0 => 
  array (
    0 => 'SERVICE 1',
    'cwa' => 'SERVICE 1',
  ),
  1 => 
  array (
    0 => 'SERVICE 2',
    'cwa' => 'SERVICE 2',
  ),
  2 => 
  array (
    0 => 'SERVICE 3',
    'cwa' => 'SERVICE 3',
  )
)

$result = $conn->query($sql);


$anames = array();


while ($row = mysqli_fetch_array($result))
{
    $anames[] = $row;
}

foreach($anames as $key => $value) {
    echo($key);
}

If you have the array like you shown in question and name $anames then do this.

Using the associative index:

foreach($anames as $key => $value) {
    echo $value['cwa']; //SERVICE 1, SERVICE 2, SERVICE 3
}

OR, using the non-associative index:

foreach($anames as $key => $value) {
    echo $value[0]; //SERVICE 1, SERVICE 2, SERVICE 3
}

Use echo $value[0]; / echo $value[cwa]; instead of echo($key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM