Using below code I am trying to get the array for each key each in side for loop, but at last the array result is wrong. The DataIds returned is merged from all the arrays, I want to get the elements from single array. Not sure how to achieve using above code in PHP? Need help? In this for each loop I want the ids to be attached to that particular key.
$student = [ABC, DEF];
public function getData()
{
$newData = $newDataId = $newDataStudIds = $DataIds = [];
foreach ($student as $key => $value) {
$Ids = [69, 70 ,71];
//for above Ids foreach is executed
foreach ($Ids as $Id) {
$data = $this->api->request('marks', [
'Id' => $Id,
'teacherId' => 1
]);
if ($data != 'error') {
$body = json_decode($data->getBody(), true);
foreach ($body['student'] as $student) {
$newData[$body['profile']['stud_id']][] = $student['stud_id'];
/* so $newData will contain
array(69 => array('0'=>1,'1'=>"2"),
70 => array('0'=>2,'1'=>"3"),
71 => array('0'=>3,'1'=>"1")
)*/
}
}
}
$newDataId = array_keys($newData);
$newDataStudIds = array_values($newData);
$DataIds = $this->implodeAllArray(',', $newDataStudIds);
$DataIds = implode(',',array_unique(explode(',', $DataIds)));
/*
i want $DataIds = [69] => [1 ,2]
[70] => [2, 3]
[71] => [3, 1]
But this $DataIds return array like
[69] => [1, 2 ,2 ,3]
[70] => [1, 2 ,2 ,3]
[71] => [1, 2 ,2 ,3]
*/
}
}
public function implodeAllArray($glue, $arr){
for ($i=0; $i<count($arr); $i++) {
if (@is_array($arr[$i]))
$arr[$i] = $this->implodeAllArray($glue, $arr[$i]);
}
return implode($glue, $arr);
}
i want $DataIds =
[69] => [1 ,2]
[70] => [2, 3]
[71] => [3, 1]
But this $DataIds return array like
[69] => [1, 2 ,2 ,3]
[70] => [1, 2 ,2 ,3]
[71] => [1, 2 ,2 ,3]
Based on my interpretation of your question, you can convert:
$newData=array(69 => array('0'=>1,'1'=>"2"),
70 => array('0'=>2,'1'=>"3"),
71 => array('0'=>3,'1'=>"1"));
To ( $DataIds
):
array(69 => array(1,2),
70 => array(2,3),
71 => array(3,1),
)
Using:
$DataIds=array_map(function($v){return [$v[0],(int)$v[1]];},$newData);
var_export($DataIds);
I am effectively converting all strings (keys and values) to integers. Demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.