在数组数组中合并数组

Merge array in array of arrays

我目前有一个包含数组数组的数组:

    array(9) {
      ["enabled"]=>
      array(4) {
        ["title"]=>
        string(14) "Enable/Disable"
        ["type"]=>
        string(8) "checkbox"
        ["label"]=>
        string(25) "Enable"
        ["default"]=>
        string(3) "yes"
      }
    ["title"]=>
    array(5) {
    ["title"]=>
    string(5) "Title"
    ["type"]=>
    string(4) "text"
    ["description"]=>
    string(60) "This controls the title which the user sees during checkout."
    ["default"]=>
    string(18) "Retail Finance"
    ["desc_tip"]=>
    bool(true)
  }

这个数组叫做$test。现在你可以在这个数组中看到,在索引 0 处有一个名为 "enabled" 的数组,在索引 1 处有一个名为 "title" 的数组。我想在索引 0 和 1 之间拼接另一个关联数组。我在下面包括了这个:

'enable_finance_calculator' => array(
            'title' => __( 'Enable Calculator', 'woocommerce' ),
            'type' => 'checkbox',
            'label' => __( 'Enable Finance Calculator', 'woocommerce' ),
            'default' => 'yes'
        ),

通常在执行此操作时我会使用 array_splice(),但这不处理关联数组。这里最好的选择是什么?

你应该可以做到这一点(还没有测试过):

// Get first item off from index 0
$tempData = array_shift($data);

// Add new array $newData at index 0
array_unshift($data, $newData);

// Add old data again at index 0, rest of items should get an incremented index, so $newData is at 1 and ['title'] is at 2
array_unshift($data, $tempData);

有点复杂,但您可以切片和合并:

$test = array_merge(
          array_slice($test, 0, $pos=array_search('enabled', array_keys($test), true)+1, true),
          $newarray,
          array_slice($test, $pos, NULL, true)
        );
  • 搜索数组键以找到位置并切片到那个位置
  • 与新数组合并
  • 与从该位置到数组末尾的切片合并