转换Array Key中的部分字符串

时间:2014-07-29 14:05:16

标签: php arrays string key

好的,我的表格有些麻烦。表单接收如下所示的数组:

Array (
[0] => abajur-grande } abajur grande
[1] => lustre-bem-grande } lustre bem grande
)

此信息由以下表单字段发送:

<input type="hidden" name="campo[]" value="<?php echo $urlprod;?> } <?php echo $nome;?><br />" />

所以,我想做的是在数组的键中转换每个值的第一部分,就像这样,并删除&#34;}&#34;:

Array (
[abajur-grande] => abajur grande
[lustre-bem-grande] => lustre bem grande
) 

有人有想法吗?

2 个答案:

答案 0 :(得分:1)

我会使用foreach循环来解决这个问题。

$arr = array(
    'abajur-grande } abajur grande',
    'lustre-bem-grande } lustre bem grande'
);

$newArr = array();
foreach($arr as $value) {
    $parts = explode(' } ', $value);
    if(count($parts) > 1) {
        $newArr[$parts[0]] = $parts[1];
    }
}
print_r($newArr);

答案 1 :(得分:0)

您需要遍历数组并获取每个值,根据}将其拆分,并将第一部分作为键,将第二部分作为值分配给新数组。

$oldArr = array("abajur-grande } abajur grande",
                "lustre-bem-grande } lustre bem grande");   
$newArr = array();

foreach($oldArr as $key) //loop old array and retrieve each element inside $key
{
    //split $key into two pieces by "}"    
    $split = explode("}",$key); 
    //assign the first piece as key and second as value into a new array
    $newArr[$split[0]]= $split[1]; 

}
print_r($newArr);