How to get values from multidimensional array in php?

喜你入骨 提交于 2019-12-24 21:22:02

问题


i have multi dimensional array like below,

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
        )

)

I need to get the values from this array and explode the values into ability and itemname.

How to i do this?.


回答1:


Assuming $array contains your data, the following code will do it.

$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
        );
    }
}



回答2:


Try this, it works for me. I match the desired strings with a regex

<?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>';
    }
}
?>


来源:https://stackoverflow.com/questions/9029897/how-to-get-values-from-multidimensional-array-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!