I have a multidimensional array where I want to insert an other array inside it with a var array.
My aim is to insert some element array with if statement. In fact I want to build a kind of conditionnal array.
Here an example
$inserted_array[] = array(
'name' => 'name',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
);
$inserted_array[] = array(
'name' => 'name',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
);
$main_arrays[] = array(
'id' => '1234',
'title' => 'a title',
'icon' => 'icon-1',
'fields' => array(
array(
'name' => 'name',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
),
//$inserted_array here for example
array(
'name' => 'name',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
),
)
);
How can I do this kind of thing?
If you want to insert the $inserted_array
into $main_arrays[]['fields]
at a given $position
You can achieve it by using array_splice function
array_splice($main_arrays[$index]['fields'], $position, 0, $inserted_array);
$index
being the $main_arrays
index in wich you want to insert the $inserted_array
$position
being the position wich at you want to insert you're array
i belive what you want is:
$mainID = 1234;
$main_arrays[$mainID] = array(
'title' => 'a title',
'icon' => 'icon-1',
'fields' => array()
);
$main_arrays[$mainID]["fields"][] = array(
'name' => 'nameA',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
);
$main_arrays[$mainID]["fields"][] = array(
'name' => 'nameB',
'desc' => 'a description',
'id' => 'an id',
'type' => 'image',
'std' => '',
);
foreach($main_arrays as $id => $inserted_array) {
print("ID: ".$id."
");
print_r($inserted_array);
}
OUTPUT:
ID: 1234
Array
(
[title] => a title
[icon] => icon-1
[fields] => Array
(
[0] => Array
(
[name] => nameA
[desc] => a description
[id] => an id
[type] => image
[std] =>
)
[1] => Array
(
[name] => nameB
[desc] => a description
[id] => an id
[type] => image
[std] =>
)
)
)