I am trying to generate an array with a specific structure using data from other arrays. I've been playing around with this code a lot and can't seem to figure it out.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);
$detList = array(
'0' => array('0' => 'NULL'),
'1' => array(
'0' => '1',
'1' => '2',
'2' => '3',
'3' => '4',
)
);
$ydata = [];
$rawxdata = '["2018-09-30 18:50:58","2018-09-30 18:53:36"]';
$rawydata = '{"12345678":{"2018-09-30 18:50:58":["1","1","1","1"]},"87654321":{"2018-09-30 18:53:36":["2","2","2","2"]}}';
$data = json_decode($rawydata);
$data = json_decode(json_encode($data), true);
$xData = json_decode($rawxdata);
$xData = json_decode(json_encode($xData), true);
echo '<pre>';
print_r($detList);
print_r($xData);
print_r($data);
$dataKey = [];
foreach($data as $key => $value){
array_push($dataKey, $key);
}
for($j=0;$j<count($xData);$j++){
for($k=0;$k<(count($detList[1])*count($data));$k++){
if(!isset($ydata[$j])){
$ydata[$j] = array();
}
$key = $dataKey[$j];
array_push($ydata[$j], (isset($data[$key][$xData[$j]][$k]) ? $data[$key][$xData[$j]][$k] : 'NULL'));
}
}
print_r($ydata);
The output of $ydata that I'm trying to achieve is
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 'NULL'
[5] => 'NULL'
[6] => 'NULL'
[7] => 'NULL'
)
[1] => Array
(
[0] => 'NULL'
[1] => 'NULL'
[2] => 'NULL'
[3] => 'NULL'
[4] => 2
[5] => 2
[6] => 2
[7] => 2
)
)
Right not I'm getting
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 'NULL'
[5] => 'NULL'
[6] => 'NULL'
[7] => 'NULL'
)
[1] => Array
(
[0] => 2
[1] => 2
[2] => 2
[3] => 2
[4] => 'NULL'
[5] => 'NULL'
[6] => 'NULL'
[7] => 'NULL'
)
)
All the arrays are dynamically generated and maintain the following logic:
Each index of $rawydata will be an array with the same number of indexes as $rawxdata. Each $rawydata[n][n] will be an array with the same number of indexes as $detList[1].
Concentrating on below single line of code:
array_push($ydata[$j], (isset($data[$key][$xData[$j]]) ? $data[$key][$xData[$j]][$j] : 'NULL'));
The value of data[$key][$xData[$j][$j]
is same for all iterations of inner loop as both $key and $j are dependent on outer loop which is constant in inner loop.
I believe you need to check your condition isset($data[$key][$xData[$j]]
please replace the line
array_push($ydata[$j], (isset($data[$key][$xData[$j]]) ? $data[$key][$xData[$j]][$j] : 'NULL'));
with this one
array_push($ydata[$j], (isset($data[$key][$xData[$j]][$k]) ? $data[$key][$xData[$j]][$j] : 'NULL'));