1

I am using PDO statement like below

$sql1 = "select food_typename from foodtypes WHERE 1";
$statement1 = $pdo->prepare($sql1);
$statement1->execute();
$results1 = $statement1->fetchAll(PDO::FETCH_ASSOC);
print_r($results1);

I am getting output as below:

Array
 (
[0] => Array
    (
        [food_typename] => Punjabi
    )

[1] => Array
    (
        [food_typename] => Indian
    )
 )

I want it be like

Array('Punjabi','Indian')

Any suggestions please?

3 Answers 3

2

If you're running PHP >= 5.5

$results = array_column($results1, 'food_typename');

If you're running earlier versions of PHP,

$results = array_map(
    $results1, 
    function($value) {
        return $value['food_typename'];
    }
);

Though I don't really understand why you can't work with the original array in the first place

Sign up to request clarification or add additional context in comments.

2 Comments

@Jake - I have a suspicion that the OP wants to use a foreach loop to present the results, and doesn't understand how to access values in a multidimensional array, so the whole question is pretty moot anyway
@mark baker .. I am not finding out anyway to iterate through this multidimensional array as i have to use in_array() function to detect values.. So decided to go via simple array
0

You can use array_map but foreach works just as well and actually runs faster than array_map for cases like this:

// Set a test array.
$results1 = array();
$results1[] = array('food_typename' => 'Punjabi');
$results1[] = array('food_typename' => 'Indian');

// Set the final reults in an array.
$results_final = array();
foreach ($results1 as $results1_value) {
  $results_final[] = $results1_value['food_typename'];
}

// Dump the line array for debugging.
echo '<pre>';
print_r($results_final);
echo '</pre>';

And the output of that would be:

Array
(
    [0] => Punjabi
    [1] => Indian
)

Comments

0

The query way:

SELECT GROUP_CONCAT(food_typename), 1 AS dummy
FROM foodtypes
GROUP BY dummy 

Then you need to retrieve the first field of the only record you will get back from mysql, and turn it into an array: see return group_concat data as array

Comments

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.