create php array from duplicate key value pairs - php

I have a json response from backend like this:
[{"studentID":"1","subjectID":"2","marks":65},
{"studentID":"1","subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80},
{"studentID":"2","subjectID":"3","marks":82},
{"studentID":"3","subjectID":"2","marks":"82"},
{"studentID":"3","subjectID":"3","marks":"75"}]
but i want to have it like this:
[{"studentID":"1","subjectID":"2","marks":65,"subjectID":"3","marks":75},
{"studentID":"2","subjectID":"2","marks":80,"subjectID":"3","marks":82}
{"studentID":"3","subjectID":"2","marks":"82","subjectID":"3","marks":"75"}]
Any idea on how to achieve this from the given array?

As mentioned you can't have duplicate keys in each object. You need to rebuild it in to something you can use. Something like this maybe:
$data = json_decode('[{"studentID":"1","subjectID":"2","marks":65},{"studentID":"1","subjectID":"3","marks":75},{"studentID":"2","subjectID":"2","marks":80},{"studentID":"2","subjectID":"3","marks":82},{"studentID":"3","subjectID":"2","marks":"82"},{"studentID":"3","subjectID":"3","marks":"75"}]');
$students = [];
foreach($data as $d) {
// If entry for student does not exist, create it
if(!isset($students[$d->studentID])) {
$students[$d->studentID] = ["subjects" => []];
}
// Add data to correct subject
$students[$d->studentID]['subjects'][$d->subjectID] = [
"marks" => $d->marks
];
}
echo json_encode($students);
// Output is: {"1":{"subjects":{"2":{"marks":65},"3":{"marks":75}}},"2":{"subjects":{"2":{"marks":80},"3":{"marks":82}}},"3":{"subjects":{"2":{"marks":"82"},"3":{"marks":"75"}}}}
Then you could access your data with $students[studentID]['subjects'][subjectId]['marks']

Related

php filtering json file and returning an attribute value

I have a json file which I read in. I want to first filter the json data to return the object defined by the datasetID, then get out the datasetName. I have filtered in javascript, but would prefer to stay in php but I can't figure it out, any ideas?
note: foreach is not required as only a single record is returned when filtered using the datasetID. So rather than using a foreach method how would you swelect a single record, first for instance?
$datasetID = '5fd4058e5c8d2'; // unique 13 character string
$data = json_decode(file_get_contents(path/to/file), True);
So I need to first filter for the unique object with $datasetID = '5fd4058e5c8d2';
$filtered_data =
Then I need to return the attribute datasetName from that object
$datasetName =
pointers to the best ways to do this is welcomed.
Sample json data:
[
[
{
"datasetID":"5fd4124900827",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None"
}
],
[
{
"datasetID":"5fd4058e5c8d2",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None",
}
]
]
I don't know how you got that JSON but it is nested deeper than needed. You can merge the top level arrays to flatten it, then index on datasetID:
$data = array_merge(...$data);
$filtered_data = array_column($data, null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Shorter:
$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Or to keep them all to use:
$data = array_column(array_merge(...$data), null, 'datasetID');
$datasetName = $data[$datasetID]['datasetName'];
I tried with your sample JSON.
First, json_decode will return a PHP array to use foreach on it. I wrote a simple foreach and checked your searching ID is equal to element's datasetID. If it is equal this is the datasetName you are searching for.
<?php
$json = '[[{"datasetID":"5fd4124900827","institutionCode":"None","collectionCode":"None","datasetName":"None"}],[{"datasetID":"5fd4058e5c8d2","institutionCode":"None","collectionCode":"None","datasetName":"None"}]]';
$elements = json_decode($json,TRUE);
$searchingID = "5fd4058e5c8d2";
foreach ($elements as $element) {
if(isset($element[0]['datasetID']) && $element[0]['datasetID'] == $searchingID){
$filtered_data = $element[0];
break;
}
}
echo $filtered_data['datasetName']; // or return $filtered_data['datasetName'];
?>

How to write a variable in the array

I try to write a string into a variable in between an array
if ($row_klasse['RabKlNummerVK'] != ''){
$headerrabklasse = '\'Rabatt\'\=\>\'price\'\,';
}
else {$headerrabklasse = '';}
then I want to write the variable $headerrabklasse in:
$writer = new XLSXWriter();
$writer->writeSheetHeader (Preisliste, array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
$headerrabklasse
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0] );
And I always get an error...
HAs anybody an idea?
In PHP you can easily append data to array like this:
//Define array with default values
//BTW: if you work with PHP >= 5.4 better to use [] instead of array()
$sheetHeaders = array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'
);
if ($row_klasse['RabKlNummerVK'] != ''){
//Here you append data to existing array in format: array[key] = value
$sheetHeaders['Rabatt'] = 'price';
}
//Then use fulfilled array as you want
$writer->writeSheetHeader ($preisliste, $sheetHeaders);
Your array takes keys and values, so you need to write a key name, and pass the variable as a value. I also noticed you were mixing Array declarations. In PHP you can call an array like this:
Array(el1, el2, ...)
or like this:
[el1, el1, ...]
Either one is fine, but for best practices you want to pick one and stick with it.
$writer->writeSheetHeader(Preisliste, [
'Marke'=>'string',
...
'MyNewKeyName' => $headerrabklasse,
...
],
[
...
]
);
I guess you wan't to do this one:
if ($row_klasse['RabKlNummerVK'] != '') {
$headerrabklasse = ['Rabatt' => 'price'];
}
else {$headerrabklasse = [];}
You could do stuff like that:
$writer->writeSheetHeader (Preisliste, array_merge(array(
'Marke'=>'string',
'Range'=>'string',
'Artikelnummer'=>'string',
'Bezeichnung'=>'string',
'EAN'=>'string',
'kg netto'=>'zahl3',
'VE'=>'string',
'Steuer'=>'string',
'Listenpreis'=>'euro',
'Nettopreis'=>'price3',
'UVP'=>'price'),
['auto_filter'=>true, 'widths'=>[20,50,15,45,15,8,8,8,8,8],
'font-style'=>'bold', 'fill'=>'#eee',
'freeze_rows'=>1,
'freeze_columns'=>0]), $headerrabklasse);

PHP - Associative array

Consider the structure for an associative array and a function which are composed by structure below:
$myCars = array("name" => "categories", "data" => array());
function getCategoriesData()
{
// data is gathered here
return $categoriesData
}
The “data” array should be populated with the return of the “getCategoriesData” function.
Considering that, how can I perform that action using a foreach loop?
Assuming that getCategoriesData() returns an Array, if you specifically need to use a foreach loop, we can write the code like this
$returnedArray = getCategoriesData();
foreach($returnedArray as $key => $value)
{
$myCars["data"][$key] = $value;
}
An even simpler approach would be this.
$mycars["data"] = getCategoriesData();

How to manipulate this array?

I am a beginner in PHP. I am trying to make an operation in this array. I want to insert this array in my database like on to many in a table.But before the insertion i have to modify the array values.
this is my array.
$services=[0=>('id_e'=>91701,'id_s'=03),
1=>('id_e'=>'','id_s'=>01),
2=>('id_e'=>'','id_s'=>02)
];
It has to become like as follow.
$services=[0=>('id_e'=>91701,'id_s'=>03),
1=>('id_e'=>'91701','id_s'=>01),
2=>('id_e'=>'91701','id_s'=>02)
];
And then i want insert into the database. Any idea please?
Try this:
$id_e = null;
foreach ($services as &$row) {
if ($row['id_e']) $id_e = $row['id_e'];
else $row['id_e'] = $id_e;
}
unset($row);
demo

update element in php foreach

I know this should be very simple, but boy I'm making a mess of it... would be great if someone could point me in the right direction.
I've got an array which looks like this:
print_r($request_attributes['length']);
Array
(
[0] => 28.00000
[1] => 18.00000
)
and am trying to modify like so:
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $request_attributes['length'][0];
print($request_attributes['length']);
$request_attributes['length'] = $request_attributes['length'][1];
print($request_attributes['length']);
}
which gives the correct output in the first update, but the second item outputs an '8'. I've tried the above in both a for and foreach which results in similar output for both this and the other two arrays ( width(8) and height(0) - they should result in 18.00000 and 13.00000 respectively ). So I guess I really have two questions:
1. How do I update this(these) element(s)?
2. Where are the funny outputs actually coming from?
If anyone can help, I'd really appreciated it.
Just have a look at this. Your problem is, that you override you variable and in the second step $request_attributes['length'] is a string. Just define another var for your values.
$request_attributes['length'] = [
28.000,
18.000
];
$attributes = array();
if (is_array($request_attributes['length'])) {
foreach ($request_attributes['length'] as $value) {
$attributes[] = $value;
}
}
As you see $attributes will contain all values of your $request_attributes['length'] array and will not be overwritten.
Define araay as below
$val=array([0]=>"18.000",[1]=>13.000)
then use
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
}
Previously your array doesnt have any name.
Your print will only return Just array not the values
use
print_r($request_attributes['length']) ;
instead

Categories