从数组创建关联数组

时间:2011-09-05 05:01:10

标签: php arrays

如何转换

Array1
(
    [0] => Some Text
    [1] => Some Other Text (+£14.20)
    [2] => Text Text (+£26.88)
    [3] => Another One (+£68.04)
)

进入如下所示的关联数组:

Array2
(
    [Some Text] => 0 //0 since there is no (+£val) part
    [Some Other Text] => 14.20
    [Text Text] => Text Text 26.88
    [Another One] => 68.04
)

2 个答案:

答案 0 :(得分:2)

$newArray = array();
foreach( $oldArray as $str ) {
    if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
        $newArray[ $matches[1] ] = (double)$matches[2];
    } else {
        $newArray[ $str ] = 0;
    }
}

答案 1 :(得分:1)

这样的事情应该有效:

$a2 = array();
foreach ($Array1 as $a1) {
    if (strpos($a1, '(') > 0) {
      $text = substr($a1, 0, strpos($a1, '('));
      $value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
    } else {
      $text = $a1;
      $value = 0;
    }
    $a2[$text] = $value;    
}
print_r($a2);

编辑:

您也可以使用explode方法执行此操作:

$a2 = array();
foreach ($Array1 as $a1) {
    $a1explode = explode("(", $a1, 2);
    $text = $a1explode[0];
    if ($a1explode[1]) {
       $value = substr($a1explode[1],3);
    } else {
       $value = 0;
    }
    $a2[$text] = $value;    
}
print_r($a2);