I'm having an array called $request
as follows:
Array
(
[op] => edit
[contact_label] => 1
[80] => on
[79] => on
[76] => on
[74] => on
[73] => on
)
Now what I want to achieve is two things as follows:
Create a new simple array having name $enquiries
which would contain all the numbers (keys from above array) i.e. 73,74,76, 79 and 80.
Create a new key within this array called [enquiries]
which would hold all the above said numbers. Also remove the current keys with numbers from the $request array.
Can anyone help me in this regard?
Try this Fiddle
<?php
$request = array( 'op' => 'edit'
,'contact_label' => 1
,80 => 'on'
,79 => 'on'
,76 => 'on'
,74 => 'on'
,73 => 'on'
);
$enquiries = array();
foreach($request as $key => $value) {
if(is_numeric($key)) {
$enquiries[] = $key;
unset($request[$key]);
}
}
$request['enquiries'] = $enquiries;
echo "<pre>";
print_r($request);
?>
Output
Array
(
[op] => edit
[contact_label] => 1
[enquiries] => Array
(
[0] => 80
[1] => 79
[2] => 76
[3] => 74
[4] => 73
)
)
You can use array_keys()
to store the keys of one array into another.
So what you could to do store the keys in your original array would be something like:
$request_keys = array_filter(array_keys($request), function($k){ return is_int($k); });
$request['enquiries'] = $request_keys;
$request = array_filter($request, function($k){ return !is_int($k); });
Edit: Filters numeric only keys for the enquiries index and also removes the numeric keys from the $requests array after the process.
$enquiries = array();
foreach($request as $key => $value) {
if(is_numeric($key) {
$enquiries[] = $key;
unset($request[$key]);
}
}
$request['enquiries'] = $enquiries;
$array = array( 'op' => 'edit'
,'contact_label' => 1
,80 => 'on'
,79 => 'on'
,76 => 'on'
,74 => 'on'
,73 => 'on'
);
foreach( $array as $key => $value ) {
if ( is_numeric( $key ) ) {
$array['enquiries'][] = $key;
unset( $array[$key] );
}
}
Output:
Array
(
[op] => edit
[contact_label] => 1
[enquiries] => Array
(
[0] => 80
[1] => 79
[2] => 76
[3] => 74
[4] => 73
)
)
<?php
$enquiries = array();
foreach( $request as $key => $val ) {
if ( is_numeric( $key ) ) {
array_push( $enquiries, $key );
unset( $request[$key] );
}
}
$enquiries['enquiries'] = $enquiries;