简体   繁体   English

使用一个表中的值作为另一个表中的键 (PHP)

[英]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.

相关问题 将值从一个表插入到另一个表 sql 和 php - Inserting values from one table to another table sql and php PHP根据另一个数组的值显示一个数组的特定键的值 - PHP display values of specific keys from one array based on values from another array PHP:如何使用另一个数组中的值覆盖一个数组中的值而不向数组添加新键? - PHP: How to overwrite values in one array with values from another without adding new keys to the array? Codeigniter-如何使用一个表中的外键查找另一表的ID - Codeigniter - how to use the foreign keys from one table to look for the id's of another table PHP合并2个具有不同数量元素的数组,一个元素包含$ keys,另一个元素包含$ values - PHP merge 2 arrays with different number of elements, $keys from one, $values from another 短代码获取数组,该数组从php中的一个数组获取键并从另一个数组获取值 - A short code to get an array that gets keys from one array and values from another in php 从一个表中选择所有值,从另一个表中选择一些值,并用php显示它们 - select all the values from one table and some values from another table and display them with php 用php中的另一个数组值替换一个数组键 - Replace one arrays keys with another arrays values in php PHP如何用另一个数组值替换一个关联数组键 - PHP How to replace one associative array keys with another array values PHP:如何将一个数组中的键与另一个数组中的值进行比较,并返回匹配项? - PHP: How to compare keys in one array with values in another, and return matches?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM