php multidimensional array json encode valid output - php

icant figure it out how to encode a valid json from my array
tried every posible way to encode json i had no luck
thankyou for your time
<?php
// this array is very large i used small piece as example
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(87,108,173,0,4),
array(87,108,173,0,5),
array(79,99,163,0,6),
array(79,99,163,0,7),
array(79,99,163,0,8),
array(79,99,163,0,9),
array(92,97,158,0,10),
array(92,97,158,0,11),
array(76,91,153,0,12),
array(79,99,163,0,13),
array(76,91,153,0,14),
array(92,97,158,0,15),
array(76,91,153,0,16),
array(76,91,153,0,17),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
array(133,157,215,1,53),
array(143,168,222,1,54),
array(156,180,227,1,55),
array(156,180,227,1,56),
array(142,175,243,1,57),
array(156,180,227,1,58),
array(156,180,227,1,59),
array(156,180,227,1,60),
array(133,157,215,1,61));
for ($key = 0, $size = count($listarray); $key < $size; $key++) {
$array = array_values($listarray[$key]);
$line = $array[3]+1; //+1 start counting from 1
$loc = $array[4]+1; //+1 start counting from 1
$Name = $array[0].'_'.$array[1].'_'.$array[2];
$data = new StdClass();
$data->$line->$Name = array("$loc",);
$json = json_encode($data,JSON_PRETTY_PRINT);
echo $json."<br>";
//// echo give somthing like this and it is unusable for me
//{ "1": { "87_108_173": [ "1" ] } }
//{ "1": { "87_108_173": [ "2" ] } }
//{ "1": { "87_108_173": [ "3" ] } }
//{ "1": { "87_108_173": [ "4" ] } }
//{ "1": { "87_108_173": [ "5" ] } }
//{ "1": { "87_108_173": [ "6" ] } }
////
$fh = fopen("jsonout.json", 'w')or die("Error opening output file");
fwrite($fh, json_encode($data,JSON_PRETTY_PRINT));
fclose($fh);
}// end of for loop
?>
// and contents of jsonout.json is not valid
//the out put needed as shoud be exactly like this
// json blew is manualy made with app and validated
{
"1": {
"87_108_173": [
"1",
"2",
"3",
"4",
"5",
"6"
],
"92_97_158": [
"11",
"12",
"16"
],
"79_99_163": [
"7",
"8",
"9",
"14"
],
"76_91_153": [
"13",
"15",
"17",
"18"
]
},
"2": {
"156_180_227": [
"56",
"57",
"59",
"60",
"61"
],
"142_175_243": [
"58"
],
"133_157_215": [
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"62"
],
"143_168_222": [
"55"
]
}
}

$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
);
$resultArray = array();
foreach ($listarray as $row) {
$ind = $row[3] + 1;
$name = $row[0] . '_' . $row[1] . '_' . $row[2];
$val = $row[4] + 1;
if (!isset($resultArray[$ind])) {
$resultArray[$ind] = array();
}
if (!isset($resultArray[$ind][$name])) {
$resultArray[$ind][$name] = array();
}
$resultArray[$ind][$name][] = $val;
}
echo json_encode($resultArray, JSON_PRETTY_PRINT);
You are welcome ;)

Related

PHP convert CSV to JSON multi level

I have a CSV data looks like this :
ps.csv
id|firstName|lastName|address|extId|extName
001|Kapil|Parames|address01|AA01|AA
002|David|Vuitton|address01|AA02|AA
002|David|Vuitton|address02|BB02|BB
003|Jean|Paul|address01|AA03|AA
And i need an output JSON to look like this :
[
{
"id": "001",
"firstName": "Kapil",
"lastName": "Parames",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA01",
"extName": "AA"
}]
},
{
"id": "002",
"firstName": "David",
"lastName": "Vuitton",
"address": [{
"address": "address01"
},
{
"address": "address02"
}
],
"ext": [{
"extId": "AA02",
"extName": "AA"
},
{
"extId": "BB02",
"extName": "BB"
}
]
},
{
"id": "003",
"firstName": "Jean",
"lastName": "Paul",
"address": [{
"address": "address01"
}],
"ext": [{
"extId": "AA03",
"extName": "AA"
}]
}
]
I can convert it to JSON. But the problem is i would like to add "address" and "extId", "extName" into multi level array if the person already exists in the list.
So following PHP code is working for me :
$csv = file('ps.csv');
$csvArray = [];
foreach ($csv as $line) {
$csvArray[] = str_getcsv($line, '|', ',');
}
$jsonArray = [];
for ($i = 1; $i < count($csvArray); $i++) {
$found = -1;
for ($j = 0; $j < count($jsonArray); $j++) {
if (in_array($csvArray[$i][0], $jsonArray[$j])) {
$found = $j;
}
}
if ($found < 0) {
$jsonArray[] = array(
'id' => $csvArray[$i][0],
'firstName' => $csvArray[$i][1],
'lastName' => $csvArray[$i][2],
'address' => array(
[
'address' => $csvArray[$i][3]
]
),
'ext' => array(
[
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
]
)
);
} else {
$addressArray = array(
'address' => $csvArray[$i][3]
);
$extArray = array(
'extId' => $csvArray[$i][4],
'extName' => $csvArray[$i][5]
);
array_push($jsonArray[$found]['address'], $addressArray);
array_push($jsonArray[$found]['ext'], $extArray);
}
}
echo '<pre>';
echo json_encode($jsonArray, JSON_PRETTY_PRINT);
echo '</pre>';
Is that correct or is there any other way to do ?

merge object in php

i have below json data
{
"data": [
{
"minggu a": "2",
"total a": "377033"
},
{
"minggu b": "1",
"total b": "136615"
}
]
and this is the code i made in controller
$satu= $this->model->db_week_resTender();
$arr = [];
foreach($satu as $val){
$arr['data'][] = array(
'minggu' => $val['minggu'],
'total' => $val['total']
);
}
$response = $this->set_response($arr,200);
}
how to concatenate below json data
here I issue data with a limit of 2.
{
"data": [
{
"minggu a": "2",
"total a": "377033"
"minggu b": "1",
"total b": "136615"
},
]
}
$data = '{
"data": [
{
"minggu a": "2",
"total a": "377033"
},{
"minggu b": "1",
"total b": "136615"
}
]
}';
$decoded_satu=json_decode($data,true);
$arr = [];
foreach($decoded_satu['data'] as $key=> $val){
foreach ($val as $subkey => $subvalue) {
$arr['data'][$subkey] = $subvalue;
}
}
$finalArray = json_encode($arr);
echo "<pre>";print_r($finalArray) ;die;
foreach($statu as $index => $val){
$arr['data'][$index] = $val;
}
This should give the result you have posted at the end.

PHP How to get a particular JSON values/parameter

This is my JSON Response came from an URL API. I use GuzzleHttp\Client and json_decode() inorder to manage.
[{
"INDEX_ID": "0",
"NOTES": "0; Farming"
},
{
"INDEX_ID": "1",
"NOTES": "Fruit Name; List of Fruits;"
},
{
"INDEX_ID": "2",
"NOTES": "Apple"
},
{
"INDEX_ID": "3",
"NOTES": "Orange"
},
{
"INDEX_ID": "4",
"NOTES": "Grapes"
},
{
"INDEX_ID": "5",
"NOTES": "Mango"
},
{
"INDEX_ID": "6",
"NOTES": "Animal Name; List of Animal;"
},
{
"INDEX_ID": "7",
"NOTES": "Pig"
},
{
"INDEX_ID": "8",
"NOTES": "Goat"
},
{
"INDEX_ID": "9",
"NOTES": "Cow"
}]
But I only need to save list of Fruits in my logfile. Can someone help me how to exclude the other json parameters and get only the particular json parameters using foreach loop or any method inorder to get that result.
I just want it to be like this:
[
{
"NOTE_NO." : "001",
"CATEGORY" : "FRUITS",
"LISTS_TO_BUY" : [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
He're my codes so far:
$response_body = json_decode($json_response, true);
$json_new_param = [];
foreach ($response_body as $value) {
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
$header = [
[
'NOTE_NO.' => '001',
'CATEGORY' => 'FRUITS',
'LISTS_TO_BUY' => $json_new_param
]
];
echo json_encode($header);
$json_response is the response given above.
You might use array_reduce to return an array where the key will be the first word from the value using implode which has this structure: "NOTES": "Fruit Name; List of Fruits;". The key for this would then be "Fruits".
During the array_reduce keep track of the current key using a variable $currKey
At the end you could then get the data by using "FRUIT" (Which is the first word) as the array key: $response_body["FRUIT"]
$response_body = json_decode($json_response, true);
$currKey = "0";
$response_body = array_reduce($response_body, function ($carry, $item) use (&$currKey){
if (strpos($item['NOTES'], 'Name; List') !== false) {
$currKey = strtoupper(explode(" ", $item["NOTES"], 2)[0]);
return $carry;
}
$carry[$currKey][] = ["FRUITS" => $item["NOTES"]];
return $carry;
});
$result = [
[
"NOTE_NO" => "001",
"CATEGORY" => ($name = "FRUITS"),
"LISTS_TO_BUY" => $response_body["FRUIT"]
]
];
echo json_encode($result, JSON_PRETTY_PRINT);
That will result in:
[
{
"NOTE_NO": "001",
"CATEGORY": "FRUITS",
"LISTS_TO_BUY": [
{
"FRUITS": "Apple"
},
{
"FRUITS": "Orange"
},
{
"FRUITS": "Grapes"
},
{
"FRUITS": "Mango"
}
]
}
]
Demo
Try this code .
$json_new_param = [];
$fruitFlag = false;
foreach ($response_body as $value) {
if(strpos($value['NOTES'],'Fruit Name') !== false){
$fruitFlag = true;
continue;
}
if(strpos($value['NOTES'],'Animal Name') !== false){
$fruitFlag = false;
}
if($fruitFlag == true){
$json_new_param[] = [
'FRUITS' => $value['NOTES']
];
}
}
echo json_encode($json_new_param, JSON_PRETTY_PRINT);

create nested json array with php

I am newbie to php ,trying to create a nested json array in php but not getting the desired json format.
desired format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"price": "1980",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"storeId": "3",
"price": "2970",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": [
{
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
},
{
"0": {
"filter": "red",
"filterId": "13"
},
"1": {
"filter": "blue",
"filterId": "14"
},
"filterName": "colour"
}
]
}
but getting this format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p1.jpg",
"brandId": "5",
"storeId": "3",
"price": "1980",
"offer": "Off-20",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p2.jpg",
"brandId": "5",
"storeId": "3",
"price": "2970",
"offer": "Off-30",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": {
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
}
}
my php code is below
$dbFactory = new DBFactory();
$jsonArray = array();
if ($subcatid != '')
{
$p2 = $dbFactory->sel_product3($subcatid, $area_value);
if (count($p2) > 0)
{
for ($j = 0; $j < count($p2); $j++)
{
$p3 = $dbFactory->sel_store($p2[$j]['STORE_ID']);
$temp['offers'][] = array(
"offerId" => $p2[$j]['P_ID'],
"offerName" => $p2[$j]['P_NAME'],
"image" => $url . $p2[$j]['P_ID'] . '.jpg',
"brandId" => $p2[$j]['BRAND_ID'],
"storeId" => $p2[$j]['STORE_ID'],
"price" => $p2[$j]['PRICE'],
"offer" => $p2[$j]['OFFER'],
"storeName" => $p3[0]['S_NAME']
);
$jsonArray = $temp;
}
}
}
// filters code=================
/*code to retrive brnads and stores goes here*/
foreach($res as $value)
{
$br = $dbFactory->sel_brand($value);
$temp["brands"][] = array("brandName" => $br[0]['BRAND_NAME'] ,"brandId"=>$br[0]['BID'] );
$jsonArray = $temp;
}
foreach($store_value as $value)
{
$sr = $dbFactory->sel_store($value);
$temp["stores"][] = array("storeName" => $sr[0][S_NAME] ,"storeId"=>$sr[0][S_ID] );
$jsonArray = $temp;
}
$parentCatId = $dbFactory->getparentcatId($subcatid);
$fg = $dbFactory->get_filtergroup($parentCatId[0]['PARENT_ID']);
for ($i = 0; $i < count($fg); $i++)
{
$f = $dbFactory->sel_filter($fg[$i][F_ID]);
$temp['filters'] = array();
$temp['filters']['filterName'] = $fg[$i][FNAME];
for ($j = 0; $j < count($f); $j++)
{
$temp['filters'][] = array("filter"=>$f[$j][FNAME],"filterId"=>$f[$j][F_ID] );
}
array_push($jsonArray, $temp);
}
$jsonArray = $temp;
echo json_encode($jsonArray);
tried a lot to get the desired json format but failed.please help me out to solve this problem

Grouping JSON by 2 parameters

I wrote the code that selects data from database, groups array by 2 parameters (match_day and competition_id) and generates JSON
foreach ($result as $res) {
$day = date('d', $res["match_start_time"]);
$json["response"][] = array(
"competition_id" => $res["competition_id"],
"match_start_time" => $res["match_start_time"],
"match_day" => $day
);
}
$arr = array();
$arr["items"] = array();
foreach($json["response"] as $key => $item)
{
if(!isset($arr['items'][$item['match_day']][$item['competition_id']])){
$arr['items'][$item['match_day']][$item['competition_id']] = array();
$arr['items'][$item['match_day']][$item['competition_id']]['league'] = $item['competition_id'];
$arr['items'][$item['match_day']][$item['competition_id']]['day'] = $item['match_day'];
}
$arr['items'][$item['match_day']][$item['competition_id']]['matches'][] = $item;
}
$arr['items'] = array_values($arr['items']);
echo json_encode($arr);
This code gives me following JSON
{
"items": [
{
"cuefa": {
"league": "cuefa",
"day": "01",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285873500"
}
]
}
},
{
"cuefa": {
"league": "cuefa",
"day": "30",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285866000"
}
]
}
}
]
}
I can't remove competition_id inside of items array. How to change code to get following JSON?
{
"items": [
{
"block": [
{
"league": "cuefa",
"day": "01",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285873500"
}
]
}
]
},
{
"block": [
{
"league": "cuefa",
"day": "30",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285866000"
}
]
}
]
}
]
}
Add this before the json_encode:
foreach ($arr['items'] as &$item) {
$item = array('block' => array_values($item));
}

Categories