将数组转换为键值对

时间:2014-01-13 09:29:37

标签: php loops multidimensional-array foreach

我有以下数组,

Array
(
    [Char100_1] => Array
        (
            [0] => Array
                (
                    [Char100_1] => Mr S Kumar
                )

            [1] => Array
                (
                    [Char100_1] => Mr S Kumar2
                )
        )

    [Char100_13] => Array
        (
            [0] => Array
                (
                    [Char100_13] => 159.9
                )

            [1] => Array
                (
                    [Char100_13] => 119.9
                )
        )

    [Char100_14] => Array
        (
            [0] => Array
                (
                    [Char100_14] => 191.88
                )

            [1] => Array
                (
                    [Char100_14] => 143.88
                )
        )
)

是从数据库查询结果和一些循环动态创建的。

现在我想把这个数组转换成如下所示的内容,

Array
(
    [0] => Array
    (
        [Char100_1] => Mr S Kumar
        [Char100_13] => 159.9
        [Char100_14] => 191.88
    )
    [1] => Array
    (
        [Char100_1] => Mr S Kumar2
        [Char100_13] => 119.9
        [Char100_14] => 143.88
    )
)

我已经尝试过循环但它不起作用。

<?php
    /* database process to create array */
    $contentArray = array();
    foreach($newData['DataField'] as $ndata) :
        $responsedata = getAppContent($appid, $ndata);
        while($haveresult = mysql_fetch_assoc($responsedata))
        {
             $contentArray[$ndata][] = $haveresult;
        }
    endforeach;

    /* for getting resulting array start */
    $newdataArray = array();

    foreach($contentArray as $field => $value):
        $newdataArray[$field] = array();
        foreach( $value as $val ) :
             $newdataArray[$field] = $val;
        endforeach;

    endforeach;
?>

3 个答案:

答案 0 :(得分:1)

如果您无法更改查询(如评论中所示),则以下内容应该有效:

$output = array();
foreach ($array as $a) {
  foreach ($a as $k => $b) {
    if (empty($output[$k])) {
      $output[$k] = array();
    }
    $output[$k] += $b;
  }
}

答案 1 :(得分:1)

我发现你正在调换数组。即所有零下标值和所有一个下标值一起。

因此,您的外部下标应为“0”和“1”。这些在内循环中可用。因此,内部循环索引成为外部数组索引。而内循环值是一个数组,你需要取“。”的“当前”值。

/* for getting resulting array start (PHP 5.3.18) */
$newdataArray = array();

foreach($contentArray as $field => $value):
    foreach( $value as $idx => $val ): // $idx takes value 0 or 1. $val is an array
      $newdataArray[$idx][$field] = current($val);
    endforeach;

endforeach;
print_r($newdataArray);

答案 2 :(得分:0)

只要所有数组都包含相同数量的值,for循环就会执行:

$NewDataArray = array();

for ($a = 0; $a < $Numberofvaluesineacharray; $a++){
$NewDataArray[$a] = $NewDataArray[$array1[$a], $array2[$a],.....arrayn[$a];
}