将Array更改为其他格式

时间:2012-02-14 10:52:21

标签: php

Array
(
    [0] => 46-sen1-Grid1-138
    [1] => 47-sen2-Grid1-138
    [2] => 50-sen5-Grid2-144
    [3] => 51-sen6-Grid2-144
)

如何使上面的数组如下?

Array
(
    [138] => Array
        (
            [0] => 46-sen1
            [1] => 47-sen2
        )

    [144] => Array
        (
            [0] => 50-sen5
            [1] => 51-sen6
        )

)

3 个答案:

答案 0 :(得分:1)

$from = array(
    '46-sen1-Grid1-138'
    '47-sen2-Grid1-138',
    '50-sen5-Grid2-144',
    '51-sen6-Grid2-144'
);

$to = array();

foreach($from as $value) {
    $elements = explode('-',$value);
    if (!isset($to[$elements[3]])) $to[$elements[3]] = array();
    $to[$elements[3]][] = $elements[0].'-'.$elements[1];
}

答案 1 :(得分:0)

循环遍历它,解析它并生成一个新的。

以下是一个如何做到这一点的简单示例:

$arr = array("46-sen1-Grid1-138", 
    "47-sen2-Grid1-138", 
    "50-sen5-Grid2-144", 
    "51-sen6-Grid2-144");

foreach ($arr as $item) {
    $arr_n[substr($item,-3)][] = substr($item,0,7);
}

var_dump($arr_n);

答案 2 :(得分:0)

您可以使用以下代码,请对我刚刚编写基本结构的数组键和值进行检查

  $a[0] =' 46-sen1-Grid1-138';
    $a[1] = '47-sen2-Grid1-138';
    $a[2] = '50-sen5-Grid2-144';
    $a[3] = '51-sen6-Grid2-144';

  $KeyArray=array();
   foreach($a as $row)
   {
    $check=explode('-',$row);
    print_r($check);

    $KeyArray[$check[3]][] = $check[0].'-'.$check[1];

   }

   print_r($KeyArray);