首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在php中从多维数组中获取值?

如何在php中从多维数组中获取值?
EN

Stack Overflow用户
提问于 2012-01-27 14:50:50
回答 2查看 2K关注 0票数 0

我有多维数组,如下所示,

代码语言:javascript
复制
Array
(
    [14289] => Array
        (
            [0] => Ability:B,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm
            [1] => Ability:B+,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm
            [2] => Ability:B++,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm
        )

    [14279] => Array
        (
            [0] => Ability:N/S,Itemname:Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pm
            [1] => Ability:N/S+,Itemname:Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pm
            [2] => Ability:N/S++,Itemname:Session #1: Tues May 31st - Fri June 10th (1-5:30PM)#1 only: 1pm
        )

    [14288] => Array
        (
            [0] => Ability:N/S,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 1:30pm
        )

    [14291] => Array
        (
            [0] => Ability:N/S+,Itemname:Session #4: Tues July 12th - Fri July 22nd (9-2:00PM)#1 only: 1pm
        )

    [14284] => Array
        (
            [0] => Ability:N/S++,Itemname:Session #2: Tues June 14th - Fri June 24th (9-2:00PM)#1 only: 1:30pm
        )

)

我需要从这个数组中获取值,并将这些值分解为和itemname。

我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-27 15:02:47

假设$array包含您的数据,下面的代码就可以做到这一点。

代码语言:javascript
复制
$result = array();
foreach($array as $a){
    foreach($a as $l){
        list($ab, $it) = explode(",", $l, 2);
        $ab = substr($ab, strlen("Ability:"));
        $it = substr($it, strlen("Itemname:"));
        $result[] = array(
            'Ability' => $ab,
            'Itemname' => $it
        );
    }
}
票数 1
EN

Stack Overflow用户

发布于 2012-01-27 15:06:17

试试这个,它对我很管用。我使用正则表达式匹配所需的字符串

代码语言:javascript
复制
<?php
$arr[][] = 'Ability:B,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm';
$arr[][] = 'Ability:B+,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm';
$arr[][] = 'Ability:B++,Itemname:Session #3: Tues June 28th - Fri July 8th (9-2:00PM)#1 only: 2pm';

$pattern = '/Ability:(.*),Itemname:(.*)$/m';

for ($i = 0; $i < count($arr); $i++) {
    for ($j = 0; $j < count($arr[$i]); $j++) {
        preg_match_all($pattern, $arr[$i][$j], $matchResult);
        echo 'Original string: '. $arr[$i][$j].'<br>';
        echo 'Ability: '.$matchResult[1][0].'<br>';
        echo 'Itemname: '.$matchResult[2][0].'<br>';
        echo '<br><hr><br>';
    }
}
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9029897

复制
相关文章

相似问题

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