0

I have following $data array

Array
(
    [0] => Array
        (
            [match_day] => MD27
            [price] => 95.33
        )
    [1] => Array
        (
            [match_day] => MD28
            [price] => 97.82
        )
    [2] => Array
        (
            [match_day] => MD29
            [price] => 
        )
    [3] => Array
        (
            [match_day] => MD30
            [price] => 
        )
    [4] => Array
        (
            [match_day] => MD31
            [price] => 
        )
)

Now, my requirements is - replace empty entry of price attribute with previous price attribute.

2
  • Loop through with one variable which you assign the price if it isn't empty, otherwise you use the variable to assign it to the price. Done. Commented Mar 29, 2016 at 10:47
  • Use the foreach() function in PHP to loop through your array. Commented Mar 29, 2016 at 10:48

2 Answers 2

2

No need to go for for loop You can try following code:

$result = [];
array_walk($data, function($v,$k) use (&$result){
    $result[$k] = $v;
    if(!isset($result[$k]['price']) || $result[$k]['price'] == null){
        $result[$k]['price'] = $result[$k - 1]['price'];
    }
});

print_r($result);

Working Demo is Here

Sign up to request clarification or add additional context in comments.

Comments

0

Perform a foreach loop an your array, store previous price value and if the current item has empty price, use previous to replace it. Example:

$previous = 0;
foreach($data AS $key => $row) {
  if (empty($row['price']))
    $data[$key]['price'] = $previous;
  else
    $previous = $row['price'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.