简体   繁体   中英

PHP: How to reorder a two dimensional array

This is how $myArray looks like:

Array
(
    [0] => Array
        (
            [month] => 1
            [atual] => 0.00
        )

    [1] => Array
        (
            [month] => 2
            [atual] => 11970.99
        )

    [2] => Array
        (
            [month] => 3
            [atual] => 2888.00
        )

    [3] => Array
        (
            [month] => 5
            [atual] => 1500.00
        )

)

I want to "fill the gaps" of the months. That is, for those months, where we have no data (4,6,8,9,10,11,12) , I want the [atual] to be zero.

I tried:

$novo=array();

for ($i=1; $i <=12 ; $i++) {
    $mes=$myArray[$i-1]['month'];
    $atual=$myArray[$i-1]['atual'];

    if(!$mes){
        $novo[$i]=0;
    } else{
        $novo[$i]=$atual;
    }
};

But this is returning:

Array
(
    [1] => 0.00
    [2] => 11970.99
    [3] => 2888.00
    [4] => 1500.00
    [5] => 0
    [6] => 0
    [7] => 0
    [8] => 0
    [9] => 0
    [10] => 0
    [11] => 0
    [12] => 0
)

[edit] now i see you have another problem, your $myArray indexes aren't matching the months.

$myArray( 
    array('month' => 1, 'atual' => 0.00),
    array('month' => 2, 'atual' => 11970.99),
    array('month' => 3, 'atual' => 2888.00),
    array('month' => 5, 'atual' => 1500.00)
)

for($i = 1; $i <= 12; $i++){
    $novo[$i] = 0;
}

foreach($myArray as $item){
    $novo[$item['month']] = $item['atual'];
}

print_r($novo);

This worked:

$novo=array_fill(1,12,0);

for ($i=1; $i <=12 ; $i++) {
            $mes=$myArray[$i-1]['month'];
            $atual=$myArray[$i-1]['atual'];

            $novo[$mes]=$atual;

};

With this code you get the month 1 in position 1 (not in position 0); Also you only search in the array one time. It's not a beautiful solution but...

$my_array = array(
array('month'=>3,'actual'=>100)
);

$results =array();
for($i=1;$i<13;$i++){
    $results[$i] = 0;
}

foreach($my_array as $a){
    $results[$a['month']] = $a['actual'];
}
print_r($results);

I didn't fully understand your question in the first response. This code should work for you. First we will create a temporary array just to hold the month and the data in an accessible format. Then we create your array :

$temp=array();

// Populate the temp array
foreach ($myArray as $row) {
    if (is_array($row) && isset($row["month"])) {
        $temp[$row["month"]] = $row["atual"];
    }
}

// Create novo array
for ($i=0; $i <12 ; $i++) {
    $novo[$i]["month"] = $i+1;
    if (array_key_exists($i+1, $temp)) {
        $novo[$i]['atual'] = $temp[$i+1];
    } else {
        $novo[$i]['atual'] = 0;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM