-2

I need to add an item array in a exist array. When i try to add i get something like this, using array_push

Array
(
    [0] => Array
        (
            [totalp] => 3.26
            [mes] => Novembro
        )

    [1] => Array
        (
            [totalp] => 2.66
            [mes] => Dezembro
        )

    [2] => Array
        (
            [0] => Array
                (
                    [bonus] => 2.6
                )

            [1] => Array
                (
                    [bonus] => 4.16
                )

        )

)

but i need this.

Array (
    [0] => Array
        (
            [totalp] => 3.26
            [mes] => Novembro
            [bonus] => 2.6
        )

    [1] => Array
        (
            [totalp] => 2.66
            [mes] => Dezembro
            [bonus] => 4.16
        )   )

follow my code.

$arrRows = array();
while ($dados = $resultp ->fetch_array(MYSQLI_ASSOC)) {
$arrRows[] = $dados;//getting totalp and mes here
}

$arrRows1 = array();
while ($dados = $resultb ->fetch_array(MYSQLI_ASSOC)) {
   $arrRows1[]=$dados; //getting bonus here
     }

array_push($arrRows,$arrRows1); // first example, but i dont need this way.
print_r($arrRows);

thankyou

reemy
  • 79
  • 1
  • 9

5 Answers5

3

Use array_map

$res = array_map('array_merge', $arrRows, $arrRows1);

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
1
<?php

$newdata =  array (
      0 => array('totalp'=>'3.26','mes' => 'Novembro'),
      1 => array('totalp'=>'2.66','mes' => 'Dezembro')

    );



foreach($newdata as $key => $value){
    $newdata[$key]['Bonus'] = "12";
}

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

Check it On LIVE DEMO

TarangP
  • 2,711
  • 5
  • 20
  • 41
1

Here is code that add bonus in multidimensional array

<?php

    $array = array(
      array(
        "totalp" => "3.26",
        "mes" => "Novembro"
      ),
      array(
        "totalp" => "3.26",
        "mes" => "Novembro"
      )
    );


    for ($i=0; $i < sizeof($array); $i++) { 
        $array[$i]['bonus'] = "2.2"; // here is you can get output from another array or variable
    }

    echo "<pre>";
    print_r($array);
    ?>

See Output

Bilal Ahmed
  • 4,005
  • 3
  • 22
  • 42
1

Try this,

foreach($arrRows as $key=>$row){
    $arrRows[$key]['bonus'] = $arrRows1[$key]['bonus'];
}

echo "<pre>";
print_r($arrRows);
echo "</pre>";
Gayan
  • 2,845
  • 7
  • 33
  • 60
1

Use array merge like below code snippet:

$out = array();
foreach ($arrRows as $key => $value){
    $out[] = array_merge((array)$arrRows1[$key], (array)$value);
}
print_r($out);

You can check this url for reference: Array merge on multidimensional array

Patrick R
  • 6,621
  • 1
  • 24
  • 27