简体   繁体   中英

PHP split array by key

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?

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']);

If I understood your question correct.

<?php

$base = array(...); // your array

// array values
$baseArrays = array_filter($base, function($item){
  return is_array($item);
});

// not array values
$not = array_diff($base, $baseArrays);

As an alternative solution, if the fields key is always the last element of the array, you can use array_pop .

$fields = array_pop($array);

And that's it. Demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM