处理多维数组

时间:2015-05-04 13:43:34

标签: php arrays multidimensional-array

我需要推送我的数组不同的值,例如,我想要一个像:

这样的数组
     array(2) { ["A056"]=> array(1) {   
                           [0]=> string(21) "User1name firstname " } 
                           [1]=> string(21) "User2name firstname " }    
                           [2]=> string(21) "User3name firstname " } 
                ["A057 etc..."]=> array(1) { [0]=> string(21) "User1name firstname " } 
                                             [1]=> string(21) "User2name firstname " }    
                                             [2]=> string(21) "User3name firstname " } 

需要在[" A056"]数组上添加所有值。 它是一个多维数组,我该怎么办? : 我的代码是:

    for($i=0;$i<$arrLength-1;$i++){
      $arrayListeAgence= array($pieces[0]=> array($listUsers[$i]." ".$listUsers[$i+1]));
    }

为什么我只获得最后一个值(jean charles是我列表的最后一个值)?:

array(2) { ["A056"]=> array(1) { [0]=> string(21) "Jean Charles " } 

我的作品如下:

array(4) { [0]=> string(6) "A057" [1]=> string(108) "KEO/Micka/KIRAN/Maria/ATHISA/HIS/SURA/Beat/SPAR/Laura/DARTI/Sona/VANNINI/Priya" [2]=> string(6) "A058" [3]=> string(59) "KEO/Micka/KIRAN/MARIA/ATHISA/MAHIS/NICOLE/Laura" }

USERLIST数组:(需要迭代并将值放在主数组arrayListeAgence上)

    $listUsers="";
    for($k = 1,$i=0; $k <sizeof($pieces); $k+=2){

        $listUsers [$k]= explode("/", $pieces[$k]);
    $i=$i+1;
    }
    print_r($listUsers);

输出:

Array ( [1] => Array ( [0] => KEO [1] => Micka [2] => KIRAN [3] => Maria [4] => MATHISA [5] => ATHISA [6] => SUDA [7] => Beat [8] => SPAR [9] => Laurence [10] => ARTTI [11] => Sona [12] => NaNINI [13] => Priya ) [3] => Array ( [0] => KEO [1] => Micka [2] => KIRAN [3] => Maria[4] => ATHISA [5] => ATHISA [6] => NICOLE [7] => Laura) )

2 个答案:

答案 0 :(得分:0)

你走了:

<?php

$pieces = array(
    "A057",
    "KEO/Micka/KIRAN/Maria/ATHISA/MAHIS/SURA/Beat/SPAR/Laura/DARTI/Sona/VANNINI/Priya",
    "A058",
    "KEO/Micka/KIRAN/MARIA/ATHISA/MAHIS/NICOLE/Laura"
);

$arrayListeAgence = array();
$usersAdded = array();
for ($i = 0; $i < count($pieces); $i = $i + 2) {
    $key = $pieces[$i];
    $usersStr = $pieces[$i + 1];
    $users = explode('/', $usersStr);
    $arrayListeAgence[$key] = array();
    for ($j = 0; $j < count($users); $j = $j + 2) {
        $username = $users[$j];
        if (array_search($username, $usersAdded) === false) {
            $arrayListeAgence[$key][] = $username . " " . $users[$j + 1] . " ";
            $usersAdded[] = $username;
        }
    }
}
var_dump($arrayListeAgence);

答案 1 :(得分:0)

如果$arrayListeAgence是您的多维数组,则应生成您要查找的输出。

// Define the main array
$arrayListeAgence = [];

for ($i = 0; $i < sizeof($pieces); $i += 2) {
    // Define one of the pieces
    $arrayListeAgence[$pieces[$i]] = [];

    for ($j = 1; $j < sizeof($listUsers); ++$j) {
        // Define a single element
        $arrayListeAgence[$pieces[$i]][] = $listUsers[$j - 1] . ' ' . $listUsers[$j];
    }
}

以下是一个工作示例:http://ideone.com/gtYvIx