2

I have a mysql query result which I have turned into an array with:

$row = customfunction_fetch_array($results);

This is how the $row array looks:

Array(
  [0]=> Array ([Fruit]=> apple [Count]=>4 [Season]=>Summer
  [1]=> Array ([Fruit]=> grape [Count]=>1 [Season]=>Fall
  [2]=> Array ([Fruit]=> apple [Count]=>3 [Season]=>Winter
  [3]=> Array ([Fruit]=> orange [Count]=>5 [Season]=>Spring
  [4]=> Array ([Fruit]=> apple [Count]=>45 [Season]=>All
)

What I'm trying to do is loop through the unique values of a specific field and save them to a new array.

$newArray =[];
foreach( $row["Fruit"] as $myFruits){
  $newArray[] = $myFruits;
}

I get a warning of:

"Invalid argument supplied for foreach()"

4
  • @axiac It looks like it's his own function that fetches all the rows. Commented Jul 7, 2017 at 20:38
  • 1
    mysql_fetch_array() doesn't return a multi-dimensional array. How can that be how the $row array looks? Commented Jul 7, 2017 at 20:39
  • yes it is my own function but i edited my post for everyone's convenience. Commented Jul 7, 2017 at 20:40
  • Either way, the warning is about $row["Fruit"] not being an array. It is a string, so don't use foreach on it. Commented Jul 7, 2017 at 20:43

1 Answer 1

7

Given the array that you posted, there is no $row['Fruit'], there is $row[0]['Fruit'], $row[1]['Fruit'] etc...

foreach($row as $values){
    $newArray[] = $values['Fruit'];
}

However, to get all the Fruits you can simply do this:

$newArray = array_column($row, 'Fruit');
Sign up to request clarification or add additional context in comments.

3 Comments

This is wrong. $row is just one row of the table, not all the rows.
@Barmar: Not according to the array print_r() output in the question.
I misread it as mysqli_fetch_array(). I guess his php_fetch_array() fetches all the rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.