如何从PHP中的索引数组创建多维数组?

时间:2019-02-05 06:25:01

标签: php arrays multidimensional-array associative-array

  • 我有一个二维数组,其第一个维是索引数组,第二个维是关联数组。
  • 在数组中,有一些我要合并的重复字段,对于其他未重复的字段,我想制作第三维数组并将其推送到那里。

这是我的代码和数组:

整个代码正常工作,只是我的第三个维度的“数据承包商”字段无法正常工作。

        <?php
    $array=Array
    (
        "0" => Array
        (
                "sid" => 10,
                "contractorid" => 1,
                "fname" => "hi",
                "lname" => "fam",
                "sname" => "saba",
                "materialname" => "beton",
                "netweight" => 100,
            ),
        "1" => Array
        (
                "sid" => 16,
                "contractorid" => 2,
                "fname" => "a",
                "lname" => "a",
                "sname" => "khoram",
                "materialname" => "kk",
                "netweight" => 200,
            ),
        "2" => Array
        (
                "sid" => 16,
                "contractorid" => 7,
                "fname" => "a",
                "lname" => "a",
                "sname" => "khoram",
                "materialname" => "kk",
                "netweight" => 777,
            ),
        "3" => Array
        (
            "sid" => 10,
            "contractorid" => 5,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 200,
        ),
        "4" => Array
        (
            "sid" => 10,
            "contractorid" => 8,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 600,
        ),
        "5" => Array
        (
            "sid" => 15,
            "contractorid" => 9,
            "fname" => "hi",
            "lname" => "fam",
            "sname" => "saba",
            "materialname" => "beton",
            "netweight" => 400,
        ),

    );

    $finalarray[]= array();
    $sidlist= array();
    $arraycount=count($array);
    for($i=0;$i<$arraycount ;$i++) {
        array_push($sidlist,$array[$i]["sid"]);
    }
    $sidlist = array_unique($sidlist);
    $sidlistcount=count($sidlist);
    $sidlist1=array();
    foreach ($sidlist as $m){
        array_push($sidlist1,$m);
    }


    for ($i = 0;$i<$sidlistcount ; $i++){
        $id=$sidlist1[$i];
        $datacontractor[$id]= array();
        for ($j = 0;$j<$arraycount ; $j++){
            if ($id==$array[$j]["sid"]){
                $contractorid = $array[$j]["contractorid"];
                $netweight = $array[$j]["netweight"];
                $finalarray[$i]=array(
                    "sid" => $id,
                    "fname" => $array[$j]["fname"],
                    "lname" => $array[$j]["lname"],
                    "sname" => $array[$j]["sname"],
                    "materialname" => $array[$j]["materialname"],
                    "datacontractor" => $datacontractor[$id],

                );


                $datacontractor[$id]["$contractorid"]=$netweight;
                echo $id,"<br>";
            }

        }
    }

    echo '<pre>';
    print_r($finalarray);
    echo '<pre>';


这是我的这段代码输出:

,但在“数据承包商”字段中有错误答案。

Array ([0] => Array
    (
        [sid] => 10
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (
                [1] => 100
                [5] => 200

            )

    )[1] => Array
    (
        [sid] => 16
        [fname] => a
        [lname] => a
        [sname] => khoram
        [materialname] => kk
        [datacontractor] => Array
            (
                [2] => 200


            )

    )[2] => Array
    (
        [sid] => 15
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (

            )

    ))

最后我想要的输出是:

请检查并告诉我我的错是什么。

Array ([0] => Array
    (
        [sid] => 10
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (
                [1] => 100
                [5] => 200
                [8] => 600 
            )

    )[1] => Array
    (
        [sid] => 16
        [fname] => a
        [lname] => a
        [sname] => khoram
        [materialname] => kk
        [datacontractor] => Array
            (
                [2] => 200
                [7] => 777

            )

    )[2] => Array
    (
        [sid] => 15
        [fname] => hi
        [lname] => fam
        [sname] => saba
        [materialname] => beton
        [datacontractor] => Array
            (

                [9] => 400
            )

    ))

2 个答案:

答案 0 :(得分:1)

在将所有数据插入"datacontractor" => $datacontractor[$id]->之前,请将finalarray设置为$datacontractor[$id],然后在单独的循环中完成。

您的代码要比实际需要的复杂得多。

考虑以下简短版本:

$array = []; // this is just some of the fields - you can add all of then here 
$array[] = array("id"=> 10, "contractorid" => 1,"netweight" => 100);
$array[] = array("id"=> 16, "contractorid" => 2,"netweight" => 200);
$array[] = array("id"=> 16, "contractorid" => 7,"netweight" => 777);
$array[] = array("id"=> 10, "contractorid" => 5,"netweight" => 200);
$array[] = array("id"=> 10, "contractorid" => 8,"netweight" => 600);
$array[] = array("id"=> 15, "contractorid" => 9,"netweight" => 400);

$ans = [];
foreach($array as $e) {
    if (!isset($ans[$e['id']])) { // if never set do first time
        $ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => $e["netweight"])); // here you can add all your other fields as fname, lname...
    } else {
        $ans[$e['id']]["datacontractor"][$e["contractorid"]] = $e["netweight"]; // just add the new field as already set
    }
}

现在,$ans将输出您的愿望

修改

将多个contractorid值更改为此:

foreach($array as $e) {
    if (!isset($ans[$e['id']])) { // if never set do first time
        $ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => [$e["netweight"]])); // notice "contractorid" has array inside (extra "[]" around $e["netweight"])
    } else {
        $ans[$e['id']]["datacontractor"][$e["contractorid"]][] = $e["netweight"]; // append to the contractorid array
    }
}

对于重新索引$ans,请在最后执行以下操作:$ans = array_values($ans);

答案 1 :(得分:1)

您可以使用array_reduce

$data = array_reduce($array, function ($old, $new) {
    if (isset($old[$new['sid']])) {
        $new['datacontractor'] = array_merge($old[$new['sid']]['datacontractor'], [$new['netweight']]);
        $old[$new['sid']] = $new;
    } else {
        $new['datacontractor'] = [$new['netweight']];
    }
    unset($new['netweight']);
    $old[$new['sid']] = $new;
    return $old;
}, []);

$data = array_values($data);
print '<pre>';
print_r($data);
print '</pre>';