0

我有一个这样的数组;

Array
(
    [database1.table1.fieldname] => "test"
    [database1.table1.fieldname1] => "test1"
    [database2.table2.fieldname] => "test2"
)

这里对于前两个值database nametable name是相同的。字段名在这里并不重要。对于第三个值,数据库名称和表名称不同。我想要实现的是我想通过比较数据库名称和表名来将此数组拆分为单独的数组。我需要实现这样的目标;

Array
(
    [database1.table1.fieldname] => "test"
    [database1.table1.fieldname1] => "test1"
)

Array
(
    [database2.table2.fieldname] => "test2"
)

有可能做这样的事情吗?

4

2 回答 2

2

试试喜欢

foreach($my_arr as $key=>$value) {

    $new_key = explode('.',$key);
    if($new_key[0] == "datebase1" && $new_key[1] == "table1") {
         $arr1[$key] = $value;
    } elseif ($new_key[0] == "datebase2" && $new_key[1] == "table2") {
         $arr2[$key] = $value;
    }
}

或者你可以试试

foreach($my_arr as $key=>$value) {

    $new_key = explode('.',$key);
    $new_arr[$new_key[0]][$new_key[1]][] = array($key=>$value);
}
print_r($new_arr);

输出 :

Array
(
  [database1] => Array
    (
        [table1] => Array
            (
                [0] => Array
                    (
                        [database1.table1.fieldname] => test
                    )

                [1] => Array
                    (
                        [database1.table1.fieldname1] => test1
                    )

            )
    )

  [database2] => Array
    (
        [table2] => Array
            (
                [0] => Array
                    (
                        [database2.table2.fieldname] => test3
                    )

            )

    )
)
于 2013-09-05T05:11:47.193 回答
1

这里是。拿着。

function splitDatabaseArray($array)
    {
    ksort($array);
    $return = array();
    $last_database_table = array();
    foreach ($array as $index => $value)
        {
        $database_table = array();
        list($database_table[0], $database_table[1]) = explode('.', $index);
        if ($last_database_table != $database_table)
            $row = &$return[];
        $last_database_table = $database_table;
        $row[$index] = $value;
        }
    return $return;
    }

$array = array
    (
    'database1.table1.fieldname' => "test",
    'database1.table1.fieldname1' => "test1",
    'database2.table2.fieldname' => "test2");

var_dump(splitDatabaseArray($array));

http://3v4l.org/TC542

于 2013-09-05T06:37:10.327 回答