如何将数组键作为另一个数组键的值以及如何在PHP中创建新数组? [关闭]
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?
我有一个名为 现在我想要的 实现如下两件事: p>
创建一个名为 在此数组中创建一个名为 任何人都可以在这方面帮助我吗? p>
DIV> $ request code>的数组,如下所示: p> \ n
Array
(
[op] => edit
[contact_label] => 1
[80] => on
[79] => on \ n [76] => on
[74] => on
[73] => on
)
code> pre>
$ queries code>的新简单数组,其中包含所有数字( 来自数组的键)即 73,74,76,79和80 strong>。 p> li>
的新键 [查询] code>,它将包含上述所有数字。 同时使用$ request数组中的数字删除当前键。 p> li>
ol>
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;