Convert Two Associative Arrays into One Multidimensional Array PHP

php merge multidimensional array
array_combine multidimensional php
php merge multidimensional array into one
php merge array values with same keys
php array combine
php merge multidimensional array by key value
php merge associative arrays by key
array push php

I have 2 associative arrays resulting from 2 queries in JSON format below:

{
  "competence": [
    {
      "id": "21",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    },
    {
      "id": "11",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    },
    {
      "id": "26",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    }
  ],
  "schedule": [
    {
      "id": "34",
      "parent_id": "21",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    },
    {
      "id": "33",
      "parent_id": "21",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    },
    {
      "id": "32",
      "parent_id": "11",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    },
    {
      "id": "31",
      "parent_id": "26",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla"
    }
  ]
}

These 2 arrays above generated by this code:

<?php

$queryCompetence = mysqli_query($con, "SELECT `id`, `title`, `description`, `image` FROM `competence` ORDER BY `title` ASC");
$querySchedule = mysqli_query($con, "SELECT `id`, `id_competence`, `title`, `description`, `image` FROM `schedule` ORDER BY `created_date` DESC");

$competence = array();
$schedule = array();

while ($row = mysqli_fetch_assoc($queryCompetence)) {
    $competence[] = array(
        'id' => $row['id'],
        'title' => $row['title'],
        'description' => $row['description'],
        'image' => $row['image'],
    );
}

while ($row = mysqli_fetch_assoc($querySchedule)) {
    $schedule[] = array(
        'id' => $row['id'],
        'parent_id' => $row['id_competence'],
        'title' => $row['title'],
        'description' => $row['description'],
        'image' => $row['image'],
    );
}

$response['competence'] = $competence;
$response['schedule'] = $schedule;

echo json_encode($response);
die();

?>

I need to make a multidimensional array in php that will output the JSON below:

{
  "competence": [
    {
      "id": "21",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla",
      "schedule": [
        {
          "id": "34",
          "parent_id": "21",
          "title": "blabla",
          "description": "blabla",
          "image": "blabla"
        },
        {
          "id": "33",
          "parent_id": "21",
          "title": "blabla",
          "description": "blabla",
          "image": "blabla"
        }
      ]
    },
    {
      "id": "11",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla",
      "schedule": [
        {
          "id": "32",
          "parent_id": "11",
          "title": "blabla",
          "description": "blabla",
          "image": "blabla"
        },
        {
          "id": "33",
          "parent_id": "21",
          "title": "blabla",
          "description": "blabla",
          "image": "blabla"
        }
      ]
    },
    {
      "id": "26",
      "title": "blabla",
      "description": "blabla",
      "image": "blabla",
      "schedule": [
        {
          "id": "31",
          "parent_id": "26",
          "title": "blabla",
          "description": "blabla",
          "image": "blabla"
        }
      ]
    }
  ]
}

How do I achieve this? I've been searching around on the net but seems like getting no luck. Any help will be much appreciated.

Thank you.

I would index the competences by ID when looping over them, then simply adjust its array when looping over the schedules.

This way, you don't need to loop over anything twice:

while ($row = mysqli_fetch_assoc($queryCompetence)) {
  // `$competence` is now indexed by ID
  $competence[$row['id']] = [
    'id' => $row['id'],
    'title' => $row['title'],
    'description' => $row['description'],
    'image' => $row['image'],
  ];
}

while ($row = mysqli_fetch_assoc($querySchedule)) {
  $schedule[$row['id']] = [
    'id' => $row['id'],
    'parent_id' => $row['id_competence'],
    'title' => $row['title'],
    'description' => $row['description'],
    'image' => $row['image'],
  ];
  // If the parent competence exists, add the schedule to it
  if (array_key_exists($row['id_competence'], $competence)) {
    $competence[$row['id_competence']]['schedule'][] = $schedule[$row['id']];
  }
}

Then, if you don't need/want the IDs as keys when json_encode-ing back, you can use array_values:

$response['competence'] = array_values($competence);
$response['schedule'] = array_values($schedule);

PHP combine two associative arrays into one array, array_merge() is more efficient but there are a couple of options: $array1 = array( "id1" => "value1"); $array2 = array("id2" => "value2", "id3"� 0th element of array is Red Key=0 value=Red Key=1 value=Green Key=2 value=Blue Multidimensional Array in PHP. A multidimensional array is an array of arrays. We can create two-dimensional, three-dimensional and n-dimensional arrays using array function. Each array within the multidimensional array can be either indexed array or associative array.

You just need to iterate over the $schedule array, inserting its values into $competence where the id value in $competence matches the parent_id value in $schedule:

foreach ($schedule as $s) {
    // find the parent_id in $competence
    if (($key = array_search($s['parent_id'], array_column($competence, 'id'))) !== false) {
        $competence[$key]['schedule'][] = $s;
    }
}
$response = array('competence' => $competence);

Demo on 3v4l.org

array_combine - Manual, Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values. Illegal values for key will be converted to string. values If two keys are the same, the second one prevails. I needed to read CSV files into associative arrays with column headers as keys. PHP - Multidimensional Arrays. A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

I hope this will work like charm.

    $a = [
    [
          "id"=> "21",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ],
        [
          "id"=> "11",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ],
        [
          "id"=> "26",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ]
    ];

    $b = [
        [ "id"=> "34",
          "parent_id"=> "21",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ],
        [
          "id"=> "33",
          "parent_id"=> "21",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ],
        [
          "id"=> "32",
          "parent_id"=> "11",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ],
       [
          "id"=> "31",
          "parent_id"=> "26",
          "title"=> "blabla",
          "description"=> "blabla",
          "image"=> "blabla"
        ]
    ];


    $final = [];

    foreach($a as $key => $val)
    {
        $final[$key] = $val;
        foreach($b as $key1 => $val1)
        {

            if($val['id'] == $val1['parent_id'])
            {
                $final[$key]['schedule'][$key1] = $val1;
            }
        }
    }

$t = [];
$t['competence'] = $final;
echo "<pre>";
print_r(json_encode($t));

array_merge - Manual, If you want to append array elements from the second array to the first array If an array key exists in both arrays, then the element from the first array will be a key in an array, it is eventually converted to an int even if you cast it to a string or of array_unique(), because array_unique() does not work on multidimensional: Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order. Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices. NOTE − Built-in array functions is given in function reference PHP Array

array_merge_recursive - Manual, 5, PHP 7). array_merge_recursive — Merge one or more arrays recursively < ?php /** * array_merge_recursive does indeed merge arrays, but it converts values with duplicate Matching keys' values in the second array overwrite those in the first array, as is the * case with [warn] => Array // severity ( associative) ( [2]� Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one.

php array merge for associative arrays Code Example, PHP queries related to “php array merge for associative arrays” how to merge values in an array � how to combine two associative array in php merging files with posts php � combine two arrays to form associative array in to 20 php � convert stdclass object to array php � convert stdclass to json in php� Today in this tutorial we are going to merge two different arrays into single associative array in PHP. Last time i was creating travel based website and creating own engine in which the condition holiday package was to merge two different array of title an description into single array.

php merge multiple associative arrays Code Example, PHP queries related to “php merge multiple associative arrays ”. php merge array with values � how to merge values in an array � how to combine two associative array in php � how to concatenate two countable laravel � create a multidimensional array in php in foreach � create associative array php� Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call. (array_walk_recursive() is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.

Comments
  • Any reason you're not wanting to use JSON_ARRAYAGG and JSON_OBJECT?
  • Pardon me, seems like I missed something on your code. How do I put schedule array inside competence array? What I see is that competence and schedule are seperated in two different response object. Thanks.
  • @ITDudes That line $competence[$row['id_competence']]['schedule'][] = $schedule[$row['id']]; adds the schedule to the 'schedule' subarray of the matching competence. So in the end, the $competence array should be what you're expecting. Therefore, if you don't need the schedules by themselves, simply encode/return $response['competence'].
  • Great. it works, the schedule array is inside the competence now. But inside the competence array itself created a new associative "id" object, it make all the result inside competence id instead of "competence" array. Any idea to fix this?
  • @ITDudes Did you use array_values on it as suggested at the end of the answer?
  • It works as I expected now. I forgot to use array_values you mentioned earlier. thanks a lot.
  • Thank you for your answer. It works, but @Jeto's answer does a better job. I appreciate your answer.
  • No worries - note that you could include the if block inside your while loop which fetches from $querySchedule so that you wouldn't need an extra foreach loop.