Объединить массив в массив массивов

В настоящее время у меня есть массив, который содержит массив массивов:

    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, Теперь, как вы можете видеть в этом массиве, есть массив с именем "enabled" с индексом 0, и массив с именем "title" в индексе 1. Я хотел бы объединить другой ассоциативный массив между индексами 0 и 1. Я включил это ниже:

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

Обычно при этом я бы использовал array_splice(), но это не относится к ассоциативным массивам. Какой лучший вариант здесь?

1

Решение

Вид вовлечен, но вы можете нарезать и объединить:

$test = array_merge(
array_slice($test, 0, $pos=array_search('enabled', array_keys($test), true)+1, true),
$newarray,
array_slice($test, $pos, NULL, true)
);
  • Поиск по ключам массива, чтобы найти позицию и нарезать до этого
  • Объединить с новым массивом
  • Слияние со срезом от позиции до конца массива
2

Другие решения

Вы должны быть в состоянии сделать это (еще не проверял):

// 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);
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector