-2

I am getting an array similar to the following one.

{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}

If form data values are null, I want to replace that key's value with the value of the next key. Like above, after value 5, I have null values. It needs to be like this:

"final_data":["1","2","4","5","fill this with 6","remove this"]
"final_data":["1","2","4","5","6"] like this

I tried array_filter(), but it didn't help.

apaderno
  • 28,547
  • 16
  • 75
  • 90
Bhautik
  • 11,125
  • 3
  • 16
  • 38

3 Answers3

2

If the response is in json format then ...

$json = '{"form_data":["1","2","4","5","","6"],"final_data":["1","2","4","5","","6"]}';
$array = json_decode($json, TRUE);

foreach($array as $index => $a) {
  $array[$index] = array_filter($a);
}

print_r($array);

https://eval.in/866379


Update:

foreach($array as $index => $a) {
  $array[$index] = array_value(array_filter($a));
}

https://eval.in/866522

MasoodRehman
  • 715
  • 11
  • 20
1

try following code,

foreach($myarray as $key=>$value)
{
    if(is_null($value) || $value == '')
        unset($myarray[$key]);
}
Moby M
  • 910
  • 2
  • 7
  • 26
0

Try this array_filter() with array_map() and array_values()

<?php
    $array = array("form_data" => array("1","2","4","5","","6"), "final_data" => array("1","2","4","5","","6"));
    function filterMe($paraArr){
        return array_values(array_filter($paraArr));
    }
    $array = array_map("filterMe",$array);
    echo "<pre>";
    print_r($array);

check the output here https://eval.in/866401

lazyCoder
  • 2,544
  • 3
  • 22
  • 41