[英]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格式。
尽管我不明白所有这些功能的用途,但是仍然有一些建议。
所以你有一个像这样的数组:
$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"]]
要将密钥保存在数组中:
$output = array_map(function($v, $k){return[$k, $v];}, $array);
在php中尝试此方法。
array_combine()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.