phparraysassociative-arraymerging-data

Append an indexed 2d array as new associative element to an associative array


I need to restructure an array so that indexed rows of data are pushed into a new associative element called records.

Input array:

array (
  'code' => 200,
  'message' => 'OK',
  0 => 
  array (
    'title' => 'Green peppercorn and lemongrass coconut broth',
    'media' => '/posts/images/84709.jpg',
  ),
  1 => 
  array (
    'title' => 'Green peppercorn and lemongrass coconut broth',
    'media' => '/posts/images/84709.jpg',
  ),
)

Desired result:

array (
  'code' => 200,
  'message' => 'OK',
  'records' => [
    array (
      'title' => 'Green peppercorn and lemongrass coconut broth',
      'media' => '/posts/images/84709.jpg',
    ),
    array (
      'title' => 'Green peppercorn and lemongrass coconut broth',
      'media' => '/posts/images/84709.jpg',
    ),
  ),
)

It used to be two arrays; I merged with array_merge($message, $records);


Solution

  • If you want to continue with your json response then you can create a new array as like, but this example is only work for your json which you mentioned in your question:

    <?php
    $array = json_decode('{"code":200,"message":"OK","0":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},"1":{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}}
    ',true);
    
    $newArray = array(); // initialize new array 
    foreach ($array as $key => $value) {
        if(is_array($value))    { // if having array
            $newArray['records'][] = $value;
        }
        else{
            $newArray[$key] = $value;
        }
    }
    echo json_encode($newArray);
    ?>
    

    Result:

    {"code":200,"message":"OK","records":[{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"},{"title":"Green peppercorn and lemongrass coconut broth","media":"\/posts\/images\/84709.jpg"}]} Second, if you are mergin two array `array_merge($message, $records);`
    

    Second Solution (recommended), if you are combining two array and wants to add a new index records then you can also modify by adding a records index as:

    $newArray = $message;
    $newArray['records'] = $records;
    echo json_encode($newArray);