0

I got a multidimensional array as result of a json_decode:

$start=new DateTime();
$jzon='[{"latitude":41.9089983,"longitude":12.4778983,"mVersionCode":1, "data":""},
{"latitude":41.9091,"longitude":12.4781983,"mVersionCode":1, "data":""},
{"latitude":41.9087983,"longitude":12.4786,"mVersionCode":1, "data":""},
{"latitude":41.9082,"longitude":12.4793,"mVersionCode":1, "data":""},
{"latitude":41.9065,"longitude":12.4811983,"mVersionCode":1, "data":""},
{"latitude":41.9061983,"longitude":12.4819983,"mVersionCode":1, "data":""},
{"latitude":41.9063983,"longitude":12.4827983,"mVersionCode":1, "data":""},
{"latitude":41.9089983,"longitude":12.4840983,"mVersionCode":1, "data":""}]';

$arrayJson=json_decode($jzon, TRUE);

then I try different way to walk through the array and the more useful I find is this one:

if (json_last_error() === JSON_ERROR_NONE) {
    // JSON is valid
    foreach($arrayJson as $cell) {
        foreach($cell as $key=>$value) {    
            if($key=='data') {
                $value=$start->format('Y-m-d\ H:i:s');
                $start=$start->modify('+1 seconds');                    
            }
        }
    }
} else {
    echo " not valid Json";
}

I've tried some different approach to assign to the field "data" the value of start but if made a var_dump over the $arrayJson object there is not setted value!

$cell[$value]=$start; doesn't work! $value= $something; doesn't work!

1
  • 3
    Use References Change this foreach($cell as $key=>$value) to foreach($cell as $key=>&$value) and this foreach($arrayJson as $cell) to foreach($arrayJson as &$cell) Commented Feb 17, 2017 at 14:50

2 Answers 2

2

As already mentioned in comments, use by reference. There is also no need to have the inner loop, you can access the 'data' member directly:

foreach($arrayJson as &$cell)
{
    $cell['data'] = $start->format('Y-m-d\ H:i:s');
    $start=$start->modify('+1 seconds');
}
Sign up to request clarification or add additional context in comments.

Comments

1

One way to Rome: (Using references)

if (json_last_error() === JSON_ERROR_NONE) {
  // JSON is valid
  foreach($arrayJson as &$cell)//<--- reference here
  {
   $cell['data'] = $start->format('Y-m-d\ H:i:s');
   $start = $start->modify('+1 seconds');                 
  }
} else { 
  echo " not valid Json"; 
}

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.