N
N
Nikola Chutkiy2018-09-11 15:12:07
PHP
Nikola Chutkiy, 2018-09-11 15:12:07

Replacing php array element key with value of another element?

Hello!
Tell me how to solve such a problem, otherwise I have already broken my whole head.
I have an associative array:

array(2) {
  ["avto"]=>
  array(2) {
    [0]=>
    array(2) {
      ["marka"]=>
      string(4) "Opel"
      ["model"]=>
      string(5) "Kadet"
    }
    [1]=>
    array(2) {
      ["marka"]=>
      string(3) "BMW"
      ["model"]=>
      string(3) "520"
    }
  }
  ["kontakt"]=>
  array(2) {
    [0]=>
    array(2) {
      ["tel"]=>
      string(17) "+7(908) 457-40-22"
      ["mail"]=>
      string(13) "[email protected]"
    }
    [1]=>
    array(2) {
      ["tel"]=>
      string(17) "+7(908) 455-10-02"
      ["mail"]=>
      string(18) "[email protected]"
    }
  }
}

it is necessary that the keys of the elements of the array ["avto"] i.e. (0, 1 ... and an infinite set) be replaced with a value from the array ["kontakt"], or rather, with an email with the key ["mail", also in order ... that is, in the ["avto"] array, key 0 will be replaced by [email protected], key 1 by [email protected], etc. in order... how to implement this, maybe through enumeration somehow or a function???

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bears, 2018-09-11
@kolyash

$array = [
  'avto' => [
    [
      'marka' => 'Opel',
      'model' => 'Kaded',
    ],
    [
      'marka' => 'BMW',
      'model' => '520',
    ]
  ],
  'kontakt' => [
    [
      'tel' => '+7(908) 457-40-22',
      'mail' => '[email protected]',
    ],
    [
      'tel' => '+7(908) 455-10-02',
      'mail' => '[email protected]',
    ]
  ]
];

$array['avto'] = array_combine(array_column($array['kontakt'], 'mail'), $array['avto']);

print_r($array);

working example

T
TerNik, 2018-09-11
@TerNik

$newArr = array();
foreach ($avtoArr as $i => $carArr) {
  newArr[$kontaktArr[$i]["mail"]] = $carArr;
}
$avtoArr = $newArr;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question