mohit
mohit

Reputation: 290

Replace values of an array with another array in php

So, i am trying to display a chart where the profit and payout is rendering on a chart. If there is a no profit and payout value in chart then it should show 0.

I have an array with values of profit and payout with hour. Now i want to replace that array with an existing array of 0 values.

Here is my code

$a1=array();
for($i=0,$i<=24,$i++){
  $a1['hour']=$i;
  $a1['payout']='0';
  $a1['profit']='0';
}

$a2=array();
$a2['hour']='2';
$a2['profit']='300';
$a2['payout']='100';
print_r(array_replace($a1,$a2));

There is something wrong with this code. Can any1 tell me what i am doing wrong?

Upvotes: 0

Views: 49

Answers (3)

Priyesh Kumar
Priyesh Kumar

Reputation: 2857

<?php

// Initial array
$a1=array();

for($i=0;$i<=24;$i++){

    // Use hour as index of array, if you use $a2[] = array(), it works
    // But problem is when you change hours, lets say 12-24, if will cause problem

    $a1[$i] = array(
        'hour'=> $i,
        'payout'=> 0,
        'profit'=> 0
    );
}

// Array from database
$a2=array();
$a2[] = array(
    'hour'=> 2,
    'payout'=> 300,
    'profit'=> 100
);
$a2[] = array(
    'hour'=> 5,
    'payout'=> 3500,
    'profit'=> 1200
);

echo '<pre>';

// Loop through second array and check if it is there in first one.
foreach( $a2 as $item) {
    if(isset($a1[$item['hour']])) {
        // Replace the values
        $a1[$item['hour']] = $item;
    }
}
print_r($a1);
?>

You are using for loop in wrong way, SyntaxError

for($i=0;$i<=24;$i++){ // <= See semi colons

}

Upvotes: 1

zenwraight
zenwraight

Reputation: 2000

You are having a syntax error in your program.

Your working program should look something like this

    $a1=array();
    for($i=0;$i<=24;$i++){
      $a1['hour']=$i;
      $a1['payout']='0';
      $a1['profit']='0';
    }

    $a2=array();
    $a2['hour']='2';
    $a2['profit']='300';
    $a2['payout']='100';
    print_r(array_replace($a1,$a2));

Hope this helps!

Upvotes: 0

Omis Brown
Omis Brown

Reputation: 199

First of all your For Loop isn't correct ! you must replace the "," with ";"

Upvotes: 0

Related Questions