如何在PHP中爆炸数组的索引?

如何在PHP中爆炸数组的索引?

问题描述:

I have an array like

Array
(
    [select_value_2_1] =>  7
)

I want to explode index into Array ([0]=select_value, [1]=2, [2]=1)

我有一个数组,如 p>

  Array 
(\  n [select_value_2_1] => 7 
)
  code>  pre> 
 
 

我想将索引分解为 Array([0] = select_value,[1] = 2 ,[2] = 1) code> p> div>

You can't just use explode() because it will also separate select from value. You could alter your output so that instead you have array keys like selectValue_2_1.

Then you can do what you want:

$items = array('selectValue_2_1' => 1);

foreach ($items as $key => $value) {
    $parts = explode('_', $key);
}

That will yield, for example:

array('selectValue', '2', '1');

You can use array_keys() to extract the keys from an array.

Use array_keys to get your keys: http://php.net/manual/en/function.array-keys.php

Or use a foreach loop:

foreach($elements as $key => $value){
   print_r (explode("_", $key));
}

Or if you want to split the keys as in your example, use a more complex function:

foreach ($array as $key=>$value) {

    $key_parts = preg_split('/_(?=\d)/', $key);

}

If you always have the exact pattern, you could use a regular expression to extract the values:

foreach ($array as $key=>$value) {
    if(preg_match('/(select_value)_(\d+)_(\d+)/', $key, $result)) {
          array_shift($result); // remove full match
    }
}

The performance of this may suck because you have a regular expression and an array operation.

<?php
$arr=array("select_value_2_1" => 7);
$keys= array_keys($arr);
$key=$keys[0];
$new_arr=explode("_",$key);
print_r($new_arr);
?>