1

I have a seeemingly banale question and I appreciate similar threads have been opened before, but I can't get it to work, so please bear with me:

Say I have an array $field with all field names of a mySQL INSERT statement. Then I have an associative array $types containing the (mysqli prepared statement) types of these fields, like so:

<?php

$fields = ["id","name","val","city"];
$type = ["name"=>"s","id"=>"i","city"=>"s","val"=>"d"];

The $type array has all values of $fields as key, but they aren't necessaryily in the same order. How would I generate a new array with the type abbreviations of all fields ..

$fieldtypes = ["s", "i", "d", "s"]

which I could than implode into the correct type string "sids" for the prepared statement.

I have been experimenting with

$try = array_replace(array_flip($fields),$type);

as suggested here which works for the implode functionality, as the array elements are in the correct order now ...

array(4) { ["id"]=> string(1) "i" ["name"]=> string(1) "s" ["val"]=> string(1) "d" ["city"]=> string(1) "s" }

... but I'm intrigued on how I would generate an array which also as the correct keys, like so:

 array(4) { ["0"]=> string(1) "i" ["1"]=> string(1) "s" ["2"]=> string(1) "d" ["3"]=> string(1) "s" }

3 Answers3

0

Use array_reduce()

$fields = ["id", "name", "val", "city"];
$type = ["name" => "s", "id" => "i", "city" => "s", "val" => "d"];
var_dump(array_reduce($fields, fn ($result, $item) => $result .= $type[$item]));

P.S. You can make life easier for yourself and bind every single parameter as a string. You don't need to worry about integers or floats as they can be easily cast from string by MySQL.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

Just use the field name as key and generate your fieldtypes array


$fields = ["id","name","val","city"];
$type = ["name"=>"s","id"=>"i","city"=>"s","val"=>"d"];
$fieldtypes = [];

foreach($fields as $field) {

    $fieldtypes[] = $type[$field];

}

print_r($fieldtypes);

0
$fields = ["id", "name", "val", "city"];
$type = ["name" => "s", "id" => "i", "city" => "s", "val" => "d"];

Use loop over $fields using array_map and take thier types from $type array.

$fieldtypes = array_map(fn($v)=>$type[$v], $fields);
print_r(array_combine($fields, $type));

Prints:

Array
(
    [id] => s
    [name] => i
    [val] => s
    [city] => d
)

I would generate an array which also as the correct keys

print_r($fieldtypes); //Array ( [0] => i [1] => s [2] => d [3] => s ) 
XMehdi01
  • 5,538
  • 2
  • 10
  • 34