spyda46
spyda46

Reputation: 19

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);
}

Upvotes: 0

Views: 93

Answers (2)

zakhefron
zakhefron

Reputation: 1443

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

Upvotes: 0

user6364857
user6364857

Reputation:

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
}

Upvotes: 1

Related Questions