Home > Software design >  Use values from one table as keys in another (PHP)
Use values from one table as keys in another (PHP)

Time:10-30

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?

CodePudding user response:

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']);

CodePudding user response:

I guess you want to create an object array a,b and c and want to fill it with a resut right?

Your array: $x = ['a', 'b', 'c'];

Let me first explain $x.

if you var_dump this array you will get:

PHP-code

$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

$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" }

CodePudding user response:

$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);
  •  Tags:  
  • php
  • Related