1

I am running SQL select query,getting the result in below format after executing the query.

Array
(
    [0] => Array
        (
            [usertype_id] => 14
        )

    [1] => Array
        (
            [usertype_id] => 15
        )

    [2] => Array
        (
            [usertype_id] => 17
        )

)

But i need result in below format

Array
(
    [0] => 14
    [1] => 15
    [2] => 17
)

So how to loop through this to get the output in above format.

2
  • 1
    What you have tried? can you post some code here Commented Mar 7, 2019 at 10:47
  • 1
    array_column. Commented Mar 7, 2019 at 10:49

3 Answers 3

2

array_column works just fine here:

https://3v4l.org/qX46k

<?php

$input = [['usertype_id' => 14], ['usertype_id' => 15], ['usertype_id' => 17]];
$expected = [14,15,17];

$result = array_column($input, 'usertype_id');

var_dump($result === $expected);

Output for 7.1.25 - 7.3.2

bool(true)

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

Comments

0

use array array_map()

$res= array_map(function($arr=array()){
    return $arr['usertype_id'];
},$input);
print_r($res);

Comments

0

If you are using PDO, then you can do as below

<?php
$sth = $dbh->prepare("SELECT usertype_id FROM user");
$sth->execute();

/* Fetch all of the values of the first column */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($result);
?>

Reference: http://php.net/manual/en/pdostatement.fetchall.php

3 Comments

@Xatenev I am running SQL select query... Perhaps?
Please look at the question first, he clearly written "I am running SQL select query,getting the result in below format after executing the query."
@SomnathSinha Right... my bad :/. Sadly stackoverflow decides I can't change my vote anymore without you editing your answer.

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.