Assigning values to a numerical array of values a query in PHP

1

Given the marcas table of the teste_db database (for example)

| id |  marca  |

| 1  | mercedes|
| 2  |   audi  |
| 3  |   fiat  |
| 4  |   alfa  |
| ...|   ...   |
|573 | ferrari |
|574 | bentley |

and given an array with n numerical arguments such as:

$arr = array('3','23','127','574')

and assuming that the array always contains numeric arguments that can be found in the id column of the table, I would like to include in the array, for each argument of this array, the value marca whose id in the table has the same value as the array, and the result would be:

$arr = array("3"=>"fiat", "23"=>"rover", "127"=>"tata", "574"=>"bentley");

What would be the code needed for this task? PHP and mysqli.

    
asked by anonymous 07.12.2017 / 13:15

1 answer

1

If I understand correctly, you can do something like:

if ($result = mysqli_query('SELECT marca FROM marcas'))
{
    $arr = array('1', '2', '3', '4');
    $bancoDeDados = mysqli_fetch_all($result);
    $resultado = array_map(null, $arr, $bancoDeDados);

    print_r($resultado);
}

See working at Ideone | Repl.it

That the result would look something like:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => mercedes
        )

    [1] => Array
        (
            [0] => 2
            [1] => audi
        )

    [2] => Array
        (
            [0] => 3
            [1] => fiat
        )

    [3] => Array
        (
            [0] => 4
            [1] => alfa
        )

)

With the array_map function, passing the first parameter to null , a pair with the corresponding values of $arr and $bancoDeDados will be returned.

    
07.12.2017 / 14:12