如何使用 php 中的键存储每个数组值

How to store each array value with their keys in php

我想将我的变量与它们的键一起存储在数组中,例如:

filter : [ 
"0" : "test",
"1" : "you",
"2" : "php"
]

我首先有 filter[] 数组,每次更新请求时,我想用它的键向这个数组添加一个值,自动创建键。

我试过这两种方法,但它们没有存储变量键:

//$seat_filters = filter array fetched from db

$filters = array($request->input('filter'));

$filters_array = array_merge($seat_filters, $filters);

当我检查 $filters_array 的结果时,我得到:

filter : [
"test",
"you",
"php"
]

同样的事情发生在下面的数组存储值的方法中:

 array_push($seat_filters ,$request->input('filter'));

只有第二种方法更短。 仅供参考:此结果采用 JSON 格式。

要将密钥保存在数组中:

  $output = array_map(function($v, $k){return[$k, $v];}, $array);

在 php 试试这个方法。

array_combine()

虽然不明白这些是干什么的,但还是给点建议。

所以你有一个像这样的数组:

$a = ["test","you","php"];
// though it's indexes are not visible - they exist
$filter = [];
// you can see indexes in this `foreach`
foreach ($a as $k => $v) {
    echo 'Key is ', $k, '; value is ', $v;
    // now you can add both values to your filter
    $filter[] = [$k, $v];
}
print_r($filter);
echo json_encode($filter); // [[0,"test"],[1,"you"],[2,"php"]]