php 为 mysqli 准备好的语句在其他数组中按顺序排序数组

php sorting array by sequence in other array for mysqli prepared statements

我有一个看似平庸的问题,我很感激以前打开过类似的线程,但我无法让它工作,所以请耐心等待:

假设我有一个数组 $field,其中包含 mySQL INSERT 语句的所有字段名称。然后我有一个关联数组 $types 包含这些字段的(mysqli 准备语句)类型,如下所示:

<?php

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

$type 数组以 $fields 的所有值作为键,但它们不一定按相同的顺序排列。我将如何使用所有字段的类型缩写生成一个新数组 ..

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

我可以将其分解为准备好的语句的正确类型字符串 "sids"

我一直在试验

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

如建议的那样here,它适用于内爆功能,因为数组元素现在的顺序正确...

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

...但我很想知道如何生成一个数组,它也作为正确的键,如下所示:

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

使用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。您可以让自己的生活更轻松,并将每个参数绑定为一个字符串。您无需担心整数或浮点数,因为它们可以通过 MySQL.

轻松地从字符串转换而来

只需使用字段名称作为键并生成您的字段类型数组


$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);

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

使用 array_map$fields 上循环并从 $type 数组中获取它们的类型。

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

打印:

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 )