1

Simple code that i use to get array results:

require_once 'connect_to_mysql.php';
$sql = "SELECT * FROM protect";
$result = mysqli_query($conn, $sql);
$db_array = array();
    if (mysqli_num_rows($result) > 0){
        while ($row = mysqli_fetch_assoc($result)){
            $db_array[] = $row;
        }
    }
    echo '<pre>';
    print_r($db_array);
    echo '</pre>';

I get the following array from database:

Array
(
    [0] => Array
        (
            [id] => 1
            [words] => cat
            [keyword] => nice cat
        )

    [1] => Array
        (
            [id] => 2
            [words] => good dog
            [keyword] => dog training
        )

    [2] => Array
        (
            [id] => 3
            [words] => love birds
            [keyword] => birds
        )

)

i wish to get this all data in a single array like this:

Array
(
    [0] => cat
    [1] => good dog
    [2] => love birds
) 

Could you please tell how i can do so? Thank you.

1
  • Why not just only add the row words to your array here: $db_array[] = $row;?! Commented Feb 25, 2017 at 21:08

3 Answers 3

4

Change your while() loop in the following way,

while ($row = mysqli_fetch_assoc($result)){
    $db_array[] = $row['words'];
}
Sign up to request clarification or add additional context in comments.

Comments

3

Just change your query,no need to get data you don`t use

$sql = "SELECT words FROM protect";

Comments

2

You can do this with the function array_column:

$smaller = array_column($db_array, 'words')

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.