G
G
gofree2018-03-26 20:56:18
PHP
gofree, 2018-03-26 20:56:18

How to merge three arrays?

Array
(
    [0] => 80
    [1] => 80
    [2] => 90
)
Array
(
    [0] => Array
        (
            [0] => 190
            [1] => 195
        )

    [1] => Array
        (
            [0] => 200
        )

    [2] => Array
        (
            [0] => 190
            [1] => 195
        )

)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

Hello, please tell me how to combine these three arrays to get an array of the form
Array
(
    [80] => Array
                (
                    [190] => 1
                    [195] => 1
                    [200] => 2
                )
    [90] => Array
                (
                    [190] => 3
                    [195] => 3
                )
)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Epifanov, 2018-03-26
@gofree

example

A
Andrey Nikolaev, 2018-03-26
@gromdron

Alternatively, another one:

/**
 * Prepare array for our job
 */
$arrayOne = [
  0 => 80,
  1 => 80,
  2 => 90,
];

$arrayTwo = [
  0 => [
    0 => 190,
    1 => 195,
  ],
  1 => [
    0 => 200,
  ],
  2 => [
    0 => 190,
    1 => 195,
  ],
];

$arrayThree = [
  0 => 1,
  1 => 2,
  2 => 3,
];

/**
 * @var array Array with actual data in our structure
 */
$arResult = [];

foreach ( $arrayTwo as $iKeyOne => $arrayTwoElement )
{
  // if in second array exist unknown key
  if ( !array_key_exists($iKeyOne, $arrayOne) )
  {
    continue;
  }

  // if in third array exist unknown key
  if ( !array_key_exists($iKeyOne, $arrayThree) )
  {
    continue;
  }

  // if in second array no elements
  if ( empty($arrayTwoElement) || !is_array($arrayTwoElement) )
  {
    continue;
  }

  /* @var integer Key for first depth level  */
  $iLevelKey = (int) $arrayOne[ $iKeyOne ];

  /* @var integer Value for second depth level */
  $iLevelValue = (int) $arrayThree[ $iKeyOne ];

  foreach ($arrayTwoElement as $k => $v)
  {
    $arResult[ $iLevelKey ][ $v ] = $iLevelValue;
  }
}

var_dump($arResult);
/*
Will display:
array(2) {
  [80]=>
  array(3) {
    [190]=> int(1)
    [195]=> int(1)
    [200]=> int(2)
  }
  [90]=>
  array(2) {
    [190]=> int(3)
    [195]=> int(3)
  }
}
*/

A
Alexander Shaykin, 2018-03-26
@KonataDev

array_merge, array_merge_recursive

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question