I have php script which is storing data into an array and then converting into json array. Following is script
$gameTraining = array();
$index = 0;
foreach($todayTraining->toArray() as $training){
if($todayTraining[$index]['type'] === 'easy'){
$gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];
}
$index++;
}
return $gameTraining;
And following response I am getting
{
"training": {
"easy": [
{
"game_id": 12
},
{
"game_id": 6
},
{
"game_id": 26
}
]
}
}
But I would like to remove the brackets from array, so can you kindly guide me how can I do that? I would like to convert as following
{
"training": {
"easy": [
"game_id": 12,
"game_id": 6,
"game_id": 26
]
}
}
You cannot have multiple items in an array with the same key. You can make an array with the ids for the game, so this line:
$gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];
can be changed with this line:
$gameTraining['easy']['game_ids'][] = $todayTraining[$index]['game_id'];
Try something like this:
$todayTraining = [
[
'type' => 'easy',
'game_id' => 123
],
[
'type' => 'easy',
'game_id' => 456
]
];
$gameTraining = array();
$index = 0;
foreach($todayTraining as $training){
if($todayTraining[$index]['type'] === 'easy'){
$gameTraining['easy'][] = substr(json_encode(['game_id' => $todayTraining[$index]['game_id']]), 1, -1);
}
$index++;
}
echo json_encode($gameTraining, JSON_PRETTY_PRINT);
Just use below line :
$gameTraining['easy'][] = $todayTraining[$index]['game_id'];
Instead of :
$gameTraining['easy'][]['game_id'] = $todayTraining[$index]['game_id'];
Hopefully, it will work.
Related
$myArray = [
"ID" => "",
"Module" => "",
"Version"=> ""
];
Output:
[
{23,finance,1.0},
{24,finance,1.1},
{25,logistic,1.0}
]
I have an array with the given Keys like above. I need a new array that gives me the highest Version IF module is same. How would I do that?
desired Output:
[
{24,finance,1.1},
{25,logistic,1.0}
]
This is what I tried
$modulesFiltered = [];
$i = 0;
$j = 0;
foreach($modules as $module){
$modulesFiltered[$i]['ID'] = $module['ID'];
foreach($modulesFiltered as $moduleF){
if(!empty($moduleF[$j]['Module'])){
if($module[$i]['Module'] == $moduleF[$j]['Module']){
$modulesFiltered[$i]['Module'] = 'this is doubled';
}
} else {
$modulesFiltered[$i]['Module'] = $module['Module'];
}
$j++;
}
$modulesFiltered[$i]['Module'] = $module['Module'];
$i++;
}
I tried to debug your code though.The problem is that you try to access element [0] of $moduleF. You should change $moduleF[$j]['Module'] to $moduleF['Module'].
Use standard functions where possible. for finding values within (multidimensional) array's you can use array_search. The code beneath works.
Also don't compare strings with == use strcmp(str1, str2) == 0 instead
$inputArray = array(
array(
"ID" => 23,
"Module" => "finance",
"Version"=> 1.0),
array(
"ID" => 24,
"Module" => "finance",
"Version"=> 1.1),
array(
"ID" => 25,
"Module" => "logistiscs",
"Version"=> 1.0));
$output = array();
foreach($inputArray as $element)
{
$key = array_search($element["Module"], array_column($output, "Module"));
if(is_numeric($key))
$output[$key]["Version"] = max($element["Version"], $output[$key]["Version"]);
else
$output[] = $element;
}
print_r($output);
I parse Excel sheet and get this JSON:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":null,
"Groupe":{
"F":null,
"D":null
}
},
{
"A":"Sony",
"Groupe":{
"F":"T.V",
"D":"LCD"
}
},
{
"A":"Sony",
"Groupe":{
"F":"PS4",
"D":"Pro edition"
}
},
{
"A":"Sony",
"Groupe":{
"F":"Smart Phone",
"D":"Quad core"
}
}
]
Php code:
$data = [];
for ($row = 15; $row <= 25; $row++) {
$data[] = [
'A' => $worksheet->getCell('A'.$row)->getValue(),
'Groupe' => [
'F' => $worksheet->getCell('F'.$row)->getValue(),
'D' => $worksheet->getCell('D'.$row)->getValue()
]
];
}
How can I organize(sort) json depending on "A"?
I tried this but I still couldn't merge "Groupe" for same "A" together:
Take away NULL colomns.
Create a copy of the Array.
Regroup fields for same element in the new Array(this didnt work)
Code:
$data1 = [];
for ($l = 0; $l < count($data); $l++){
$data1[$l] = $data[$l];
}
for ($j = 0; $j < count($data); $j++) {
if($data[$j]['A'] != NULL){
if($data[$j]['A'] !== $data[$j+1]['A']){
$data1[$j] = $data[$j];
}
else{
$data1[$j]['A']= $data[$j]['A'];
$data1[$j]['Groupe']= array_merge($data[$j]['Groupe'], $data[$j+1]['Groupe']);
}
}
}
EDIT:
The result that I'm getting for $data1 is exactly the same as the input JSON(except that NULL was deleted), so it looks like merge Array didnt work and what I need is:
[
{
"A":"Samsung",
"Groupe":{
"F":"TV",
"D":"HDR"
}
},
{
"A":"Sony",
"Groupe": [{
"F":"T.V",
"D":"LCD"
},{
"F":"PS4",
"D":"Pro edition"
}, {"F":"Smart Phone",
"D":"Quad core"
}]
}]
Plus it's showing me this :
Notice: Undefined offset: 11 in C:\xampp\htdocs\phptoexcel.php on line
43
Line 43: if($data[$j]['A'] !== $data[$j+1]['A']){
Use the A value as key in $data, so you can group by it:
$data = [];
for ($row = 15; $row <= 25; $row++) {
//get A value, skip if A = NULL
$a = $worksheet->getCell('A'.$row)->getValue(),
if($a===NULL)continue;
//get F and D VALUE, skip if one of them = NULL
$f = $worksheet->getCell('F'.$row)->getValue();
$d = $worksheet->getCell('D'.$row)->getValue();
if($f===null || $d===null)continue;
//test if A is a key in $data. If not, create
if(!array_key_exist( $a, $data ){
$data[$a]=[
'A'=>$a,
'Groupe'=>[]
];
}
//Put F and D in a new array in Groupe
$data[$a]['Groupe'][]=["F"=>$f,"D"=>$d];
}
You will end up with:
$data=>
[ "Samsung" =>[ "A" => "Samsung",
"Groupe" => [ 0 =>[ "F" => "TV",
"D" => "HDR"
]
]
],
"Sony" => [ "A" => "Sony",
"Groupe" => [ 0 =>[ "F":"TV",
"D":"HDR"
],
1 =>[ "F":"T.V",
"D":"LCD"
],
2 =>[ "F":"PS4",
"D":"Pro edition"
],
3 =>[ "F":"Smart Phone",
"D":"Quad core"
],
]
]
Try This
$arrUnique = array();
$result = array();
$i=0;
foreach($data as $value){
if($value['A']!=null){
$data1 = [];
$intID = $value['A'];
if( in_array( $intID, $arrUnique ) ) {
$key = array_search ($intID, $arrUnique);
$result[$key]['Groupe'][] = $value['Groupe'];
}else{
$data1['A'] = $value['A'];
$data1['Groupe'][] = $value['Groupe'];
$result[$i]=$data1;
$arrUnique[]=$value['A'];
$i++;
}
}
}
I usually don't perform JSON to JSON transformation using PHP but using jq command line utility.
Given your input JSON file, you can use this jq filter:
jq '[[sort_by(.A)|.[]|select(.A!=null)]|group_by(.A)|.[]as $i|{A:$i[].A,Groupe:$i|map(.Groupe)}]|unique' file
[
{
"A": "Samsung",
"Groupe": [
{
"F": "TV",
"D": "HDR"
}
]
},
{
"A": "Sony",
"Groupe": [
{
"F": "T.V",
"D": "LCD"
},
{
"F": "PS4",
"D": "Pro edition"
},
{
"F": "Smart Phone",
"D": "Quad core"
}
]
}
]
I get an additional arraydimension and I don't really know why. This is the php code I use for my multidimensional array.
$json_arr = array(
"a" => "0",
"b" => 1,
"c" => 2);
$json_arr_d = array();
for ($i=0; $i<$rows*$cols; $i++) {
$json_arr_d[] = array(
"d1" => "$i",
"d2" => "0",
"d3" => rand(0, 2)
);
}
$json_arr_e = array();
for ($i=0; $i<6; $i++) {
$json_arr_e[] = array(
"e1" => $i,
"e2" => "0",
"e3" => rand(0, 1),
"e4" => false
);
}
$json_arr[] = array("d" => $json_arr_d);
$json_arr[] = array("e" => $json_arr_e);
$json = json_encode($json_arr);
As you can see in the following result. There are additional layers [0] and [1] for my d & e array.
{
"a":"ABXD",
"b":5,
"c":6,
"0":{ // HERE IS THE PROBLEM
"d":[
{
"d1":"0",
"d2":"1",
"d3":1
},
{
"d1":"1",
"d2":"2",
"d3":1,
}
},
"1":{ // HERE IS THE PROBLEM
"d":[
{
"d1":"0",
"d2":"1",
"d3":1,
"d4":false
},
{
"d1":"1",
"d2":"2",
"d3":0,
"d4":false
}
]
}
Maybe I am to sleepy already and it is a pretty simple solution or my way to add the arrays is fundamentally wrong.
Don't push onto the array, assign to the key you want.
$json_arr['d'] = $json_arr_d;
$json_arr['e'] = $json_arr_e;
I use TPP API for check domain availability and domain register but i receive response in string.
Get Session, return stringOK: t73484678463765
Domain check, return string woohoo123.nz: OK: Minimum=1&Maximum=2
In other case, return string woohoo123.nz: ERR: 102, This is message
When It return OK it has & in child but when ERR that time it has ,
I want convert return string into array
such as input woohoo123.nz: OK: Minimum=1&Maximum=2 and output following array
[
'woohoo123.nz' => [
'OK' => [
'Minimum' => 1,
'Maximum' => 2,
]
]
]
input woohoo123.nz: ERR: 102, This is message and output following array
[
'woohoo123.nz' => [
'ERR' => [
'code' => 102,
'message' => 'This is message',
]
]
]
I like more to reuse code, I prefer recursive and callback but not sure in this case.
Not 100% sure if this is what you are looking for. It works for your examples, but will only continue to work if the input strings follow that format strictly.
function stringToArray($inputStr) {
$array = [];
$topComponents = explode(': ',$inputStr);
$parametersStr = $topComponents[count($topComponents) -1];
if (strpos($parametersStr,'&') !== FALSE) {
$tmpArr = explode('&',$parametersStr);
foreach ($tmpArr as $val) {
$comp = explode('=',$val);
$array[$comp[0]] = $comp[1];
}
} else if ($topComponents[count($topComponents) - 2] === "ERR") {
$tmpArray = explode('ERR: ',$parametersStr);
$tmpArray = explode(', ',$tmpArray[0]);
$array = [
"code" => intval($tmpArray[0]),
"message" => $tmpArray[1]
];
} else {
$array = $parametersStr;
}
for ($i=count($topComponents) -2; $i >= 0; $i--) {
$newArray = [];
$newArray[$topComponents[$i]] = $array;
$array = $newArray;
}
return $array;
}
print_r(stringToArray("OK: t73484678463765"));
I am trying to get my JSON output like this.
{"allterms":[{"group":{"Name":"Test 1"},{"group":{"Name":"Test2","Id":"298"}}]
My current code is
while($r = mysql_fetch_assoc($rs)) {
$rows['allterms']['group'][] = $r;
}
Which gives me this
{"allterms":{"group":[{"Name":"Test1", "Id":"1740"},{"Name":"Test2","Id":"631"}}]
How can I adjust my code so that each item has a parent term group.
Change the loop like so:
while($r = mysql_fetch_assoc($rs)) {
$rows['allterms'][]['group'] = $r;
}
which will generate:
array(
'allterms' => array(
0 => array(
'group' => array(...),
),
1 => array(
'group' => array(...),
)
...
)
which as json will be:
{
"allterms": [
{
"group": {
{
"Name": "Test1",
"Id": "1740"
},
{
"group": {
{
"Name": "Test2",
"Id": "631"
}
}
]
}
You could use the array_push() function from PHP.
while($r = mysql_fetch_assoc($rs)) {
array_push($rows['allterms'], $r);
}