modifying json from php array
Get the solution ↓↓↓Solution:
You have to update your array with key. Or second option is you can create new array with your expected output key:
$array = Array
(
"1" => Array
(
"0" => "16/03/2018",
"1" => "Friday",
"2" => "21.00",
"3" => "Friendly Match",
"4" => "Italy vs France",
"5" => "Truesports HD",
),
"2" => Array
(
"0" => "17/03/2018",
"1" => "Saturday",
"2" => "15.30",
"3" => "Friendly Match",
"4" => "Italy vs Pakistan",
"5" => "Truesports HD",
),
"3" => Array
(
"0" => "17/03/2018",
"1" => "Saturday",
"2" => "19.00",
"3" => "Friendly Match",
"4" => "Spain vs USA",
"5" => "Truesports"
)
);
$array_keys= array("date","day","time","type","value","tv");
$new_array = array();
foreach ($array as $key => $value) {
$tmp_array = array();
foreach ($value as $key1 => $value1) {
if(isset($array_keys[$key1]))
$tmp_array[$array_keys[$key1]] = $value1;
}
$new_array[] =$tmp_array;
}
echo json_encode($new_array, JSON_PRETTY_PRINT);
Answer
Solution:
I usedarray_combine()
function - Creates an array by using one array for keys and another for its values
$array = array
(
"1" => array
(
"0" => "16/03/2018",
"1" => "Friday",
"2" => "21.00",
"3" => "Friendly Match",
"4" => "Italy vs France",
"5" => "Truesports HD",
),
"2" => array
(
"0" => "17/03/2018",
"1" => "Saturday",
"2" => "15.30",
"3" => "Friendly Match",
"4" => "Italy vs Pakistan",
"5" => "Truesports HD",
),
"3" => array
(
"0" => "17/03/2018",
"1" => "Saturday",
"2" => "19.00",
"3" => "Friendly Match",
"4" => "Spain vs USA",
"5" => "Truesports"
)
);
$array_keys= array("date","day","time","type","value","tv");
$newArray=array();
foreach($array as $subArr){
$newArray[] = array_combine($array_keys,$subArr);
}
echo json_encode($newArray, JSON_PRETTY_PRINT);
Answer
Solution:
Use This
$field = array("date","day","time","type","value","tv");
echo "<pre>";
foreach($yourArr as $value){
$j = 0;
foreach($value as $arrVal){
//Get Field Name
$fieldKey = $field[$j];
$newArr[$fieldKey] = $arrVal;
$j++;
}
$finalArr[] = $newArr;
}
print_r($finalArr);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: you must enable the openssl extension in your php.ini to load information from https://repo.packagist.org
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.