phparrays

Remove a specified associative element from an array and declare the removed data as a new array


I have an array which looks like this:

array (
  'id' => 1,
  'channel_id' => 1,
  'field_group' => 1,
  'url_title' => 'the_very_first_entry',
  'title' => 'The Very First Entry',
  'fields' => 
  array (
    0 => 
    array (
      'label' => 'Enter Item Name:',
      'type' => 'text',
      'channel_data_id' => 1,
      'value' => 'Item one',
      'field_id' => 1
    ),
    1 => 
    array (
      'label' => 'Enter Item Description',
      'type' => 'textarea',
      'channel_data_id' => 2,
      'value' => 'Some long text blah blah',
      'field_id' => 2
    )
   )
  )

I want to split this into 2 arrays, one containing the fields, and the other containing everything else, ie.

Array 1:

array (
  'id' => 1,
  'channel_id' => 1,
  'field_group' => 1,
  'url_title' => 'the_very_first_entry',
  'title' => 'The Very First Entry'
);

Array 2:

  array (
    0 => 
    array (
      'label' => 'Enter Item Name:',
      'type' => 'text',
      'channel_data_id' => 1,
      'value' => 'Item one',
      'field_id' => 1
    ),
    1 => 
    array (
      'label' => 'Enter Item Description',
      'type' => 'textarea',
      'channel_data_id' => 2,
      'value' => 'Some long text blah blah',
      'field_id' => 2
    )
   )

Is there a better solution that iterating through the original array with a foreach loop?


Solution

  • Is there a better solution that iterating through the original array with a foreach loop

    You know the split-key so there's no real use for foreach:

    $src = array(...);   // your source array
    $fields_array = $src['fields'];
    unset($src['fields']);