Tim
Tim

Reputation: 901

Convert a flat array into a 2d array by pushing all data into the first row of the second level

I'm trying to build something on top of a wordpress plugin. For this I need to add more content to an existing array.

This would be the current result from the array:

$formField = [
    'key' => 'my-key',
    'value' => 'my-value'
];

But I would like to get the content nested, so I can add more indexes.

This would be the disired output:

$formField = [
    '0' => [
        'key' => 'my-key',
        'value' => 'my-value'
    ]
];

I thought of this:

if ( array_key_exists('key', $formField)) {
    $formFieldTemp = $formField;
    $formField = [];
    $formField[0] = $formFieldTemp;
}

Than I can add more content with:

$formField[] = ["key" => "new-key", "value"=>"new-value"];

My question is: Isn't there a better way to nest the existing content in this array?

Upvotes: 0

Views: 63

Answers (2)

Richard Tyler Miles
Richard Tyler Miles

Reputation: 683

These three lines should do it for you. If you're sure it'f an array you can remove the first one.

is_array($formField) or $formField = [];
array_key_exists('key', $formField) and $formField = [ $formField ];
$formField[] = ["key" => "new-key", "value"=>"new-value"];`

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163632

You could wrap $formField in an array [$formField] and set it again instead of creating $formFieldTemp:

$formField = [
    'key' => 'my-key',
    'value' => 'my-value'
];

if (array_key_exists('key', $formField)) {
    $formField = [$formField];
}

print_r($formField);

Result:

Array
(
    [0] => Array
        (
            [key] => my-key
            [value] => my-value
        )

)

Upvotes: 3

Related Questions