V
V
VS2019-08-20 09:51:08
PHP
VS, 2019-08-20 09:51:08

How to make an array value a key in php?

There is an array like

$arr = [
    'Model'		=>	'OPPO',
    'Price'		=>	'300$',
    'Year'		=>	'2019',
  ];

The task at the output is to get an array like this:
$arr = [
    'OPPO' =>[
    'Price'		=>	'300$',
    'Year'		=>	'2019',
      ]
  ];

That is, make the value of the Model key the top-level element in the nested array (this is how the task sounds)
.
$arr = [
    'Model'		=>	'OPPO',
    'Price'		=>	'300$',
    'Year'		=>	'2019',
  ];

$item = [];

  foreach ($arr as $key => $value)
  {
      if ($key == 'Model')
      {
        $item[($value)] = [];
        continue;
      }
    else 
    {
        $item[($key)] = $value;
    }
      var_dump($item);
  }

But the code doesn't work correctly. I tried to write in different ways, as a result, either I received an empty OPPO array, or I received it as an array, but in order to add each next value, the array was recreated. The result is a lot of arrays, all with different values.
PS Thanks in advance, I will be very grateful for the help! And I apologize in advance for ambiguities, there is a habit of complicating)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2019-08-20
@Compolomus

$arr = [
    'Model'		=>	'OPPO',
    'Price'		=>	'300$',
    'Year'		=>	'2019',
];

$key = array_shift($arr);

$new = [$key => $arr];

echo '<pre>' . print_r($new, true) . '</pre>';

/*Array
(
    [OPPO] => Array
        (
            [Price] => 300$
            [Year] => 2019
        )

)*/

A
Artur Gilyanovsky, 2019-08-21
@arkotik

$key = 'Model';
$result = [];
if (key_exist($key, $arr)) {
    $keyVal = $arr[$key];
    $result[$keyVal] = $arr;
    unset($result[$keyVal][$key]);
}

A
Anton Dyrkov, 2019-08-21
@kavi4

use the native array_flip function, don't write a bike
https://www.php.net/manual/ru/function.array-flip.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question