[英]Use values from one table as keys in another (PHP)
我有一個數組,我想將其值用作散列中的鍵。 我有一個:
$x = ['a', 'b', 'c'];
$r = 'result;
或者
$obj=['name'=>'a/b/c', 'value'=>'result']
我想將其轉換為:
$x['a']['b']['c'] = 'result';
如何擁抱它?
您可以使用遞歸函數來完成
function convert(array $keys, $value) {
if(count($keys) === 0){
return $value;
}
$key = $keys[0];
$rest = array_slice($keys, 1);
return [$key => convert($rest, $value)];
}
在第一種情況下
$x = convert($x, $result);
第二種情況
$x = convert(explode('/', $obj['name']), $obj['value']);
我猜您想創建一個對象數組 a、b 和 c 並想用結果填充它,對嗎?
你的數組: $x = ['a', 'b', 'c'];
讓我先解釋一下 $x。
如果你 var_dump 這個數組,你會得到:
PHP代碼
$x = ['a', 'b', 'c'];
var_dump($x);
輸出:
array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }
但實際上你想創造這樣的東西?
PHP代碼
$r = 'result';
$x['a'] = $x['b'] = $x['c'] = $r;
var_dump($x);
輸出:
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.