首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数组创建关联数组

从数组创建关联数组
EN

Stack Overflow用户
提问于 2011-09-05 13:01:10
回答 2查看 115关注 0票数 0

我如何实现转型

代码语言:javascript
复制
Array1
(
    [0] => Some Text
    [1] => Some Other Text (+£14.20)
    [2] => Text Text (+£26.88)
    [3] => Another One (+£68.04)
)

转换为关联数组,如下所示:

代码语言:javascript
复制
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
)
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-05 13:37:12

代码语言:javascript
复制
$newArray = array();
foreach( $oldArray as $str ) {
    if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
        $newArray[ $matches[1] ] = (double)$matches[2];
    } else {
        $newArray[ $str ] = 0;
    }
}
票数 2
EN

Stack Overflow用户

发布于 2011-09-05 13:11:29

像这样的东西应该是有效的:

代码语言:javascript
复制
$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方法执行此操作:

代码语言:javascript
复制
$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);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7304035

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档