[英]Use values from one table as keys in another (PHP)
I have an array whose values I want to use as keys in an hash.我有一个数组,我想将其值用作散列中的键。 I have a:
我有一个:
$x = ['a', 'b', 'c'];
$r = 'result;
OR或者
$obj=['name'=>'a/b/c', 'value'=>'result']
I want to convert it to:我想将其转换为:
$x['a']['b']['c'] = 'result';
How to embrace it?如何拥抱它?
You can do it using a recursive function您可以使用递归函数来完成
function convert(array $keys, $value) {
if(count($keys) === 0){
return $value;
}
$key = $keys[0];
$rest = array_slice($keys, 1);
return [$key => convert($rest, $value)];
}
In the first case在第一种情况下
$x = convert($x, $result);
second case第二种情况
$x = convert(explode('/', $obj['name']), $obj['value']);
I guess you want to create an object array a,b and c and want to fill it with a resut right?我猜您想创建一个对象数组 a、b 和 c 并想用结果填充它,对吗?
Your array: $x = ['a', 'b', 'c'];你的数组: $x = ['a', 'b', 'c'];
Let me first explain $x.让我先解释一下 $x。
if you var_dump this array you will get:如果你 var_dump 这个数组,你会得到:
PHP-code PHP代码
$x = ['a', 'b', 'c'];
var_dump($x);
Output:输出:
array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }
But actually you wanted to create something like this?但实际上你想创造这样的东西?
PHP-code PHP代码
$r = 'result';
$x['a'] = $x['b'] = $x['c'] = $r;
var_dump($x);
Output:输出:
array(3) { ["c"]=> string(6) "result" ["b"]=> string(6) "result" ["a"]=> string(6) "result" }
$x = ['a', 'b', 'c'];
$r = 'result';
$temp = [];
for ($i = count($x)-1; $i >= 0; $i--) {
if ($i === count($x)-1) {
$temp[$x[$i]] = $r;
} else {
$temp[$x[$i]] = $temp;
unset($temp[$x[$i+1]]);
}
}
print_r($temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.