I just wanted to know is there a possibility to get specific columns from duplicated row in PHP-MySQL connection and use them to the existing data in JSON?
/...db connection etc.
if ($statement->execute())
{
$response["lecturer"] = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lecturer = array();
$lecturer["id"] = $row["lecturerid"];
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
$lecturer["field"]["fieldid"] = $row["fieldid"];
$lecturer["field"]["name"] = $row["f_name"];
array_push($response["lecturer"], $lecturer);
}
}
/... json_encode etc.
So, there can be a situation, where one lecturer has 2 different fields, and I'm getting something like this:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1"
}
},
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 14,
"name": "field2"
}
},
Instead of that, I would like to get JSON:
{
"lecturer": [
{
"id": 1,
"image": "http://...",
"degree": "PhD",
"name": "John",
"surname": "Doe",
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
},
In the MySQL database there are two tables: lecturer, and field, but also lecturer_field table, where I have relation between lecturerid and fieldid.
As i was pointed out, it's impossible to declare similar named field in json object:
"field": {
"fieldid": 13,
"name": "field1",
"fieldid": 14,
"name": "field2"
}
Valid case is
"field": [{
"fieldid": 13,
"name": "field1",
},
{
"fieldid": 14,
"name": "field2"
}]
You can do that in this way:
if ($statement->execute())
{
$indexedLecturers = array();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$lid = $row["lecturerid"];
if (isset($indexedLecturers[$lid])) {
array_push($indexedLecturers[$lid]["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
} else {
$lecturer = array();
$lecturer["id"] = $lid;
$lecturer["image"] = $row["l_image"];
$lecturer["degree"] = $row["degree"];
$lecturer["name"] = $row["l_name"];
$lecturer["surname"] = $row["surname"];
$lecturer["field"] = array();
array_push($lecturer["field"], array(
"fieldid" => $row["fieldid"],
"name" => $row["f_name"],
));
$indexedLecturers[$lid] = $lecturer;
}
}
$response['lecturer'] = array_values($indexedLecturers);
}
Related
I have a array of objects in PHP like:
[
{
"id": 99961,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667995574207
},
{
"id": 99960,
"candidate": {
"data": {
"id": 125274,
"firstName": "CHRISTIAN",
"lastName": "NEILS"
}
},
"dateAdded": 1667986477133
},
{
"id": 99959,
"candidate": {
"data": {
"id": 125273,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
{
"id": 99958,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
]
I want to find duplicates based on same candidate firstName and lastName but different candidate id's.
I have tried multiple methods like array_search, array_column, array_filter etc but nothing giving desired result.
Output should be array of candidate.data.id that are different but with same firstName and lastName.
Can anyone guide me in building the algorithm?
Group on a key which is composed of the candidate's first name and last name and push the respective id as a child of that group using the id as the key and the value -- this ensures uniqueness within the group.
Then filter out the candidates that only occur once and re-index the qualifying subsets.
Code: (Demo)
$grouped = [];
foreach ($array as $row) {
$compositeKey = "{$row['candidate']['data']['firstName']} {$row['candidate']['data']['lastName']}";
$grouped[$compositeKey][$row['candidate']['data']['id']] = $row['candidate']['data']['id'];
}
$result = [];
foreach ($grouped as $id => $group) {
if (count($group) > 1) {
$result[$id] = array_values($group);
}
}
var_export($result);
Output:
array (
'Jose Zayas' =>
array (
0 => 125275,
1 => 125273,
),
)
Or with one loop, collect all unique ids per group then push all keys into the result array if more than 1 total in the group. (Demo)
$duplicated = [];
foreach ($array as $row) {
$compositeKey = "{$row['candidate']['data']['firstName']} {$row['candidate']['data']['lastName']}";
$id = $row['candidate']['data']['id'];
$grouped[$compositeKey][$id] = '';
if (count($grouped[$compositeKey]) > 1) {
$duplicated[$compositeKey] = array_keys($grouped[$compositeKey]);
}
}
var_export($duplicated);
You need to set iteration for to pick key data (firstName and lastName) for buffer. After it, you can check key from buffer data for to find exists users. :
<?php
$arr = <<<JSON
[
{
"id": 99959,
"candidate": {
"data": {
"id": 125273,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
},
{
"id": 99961,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667995574207
},
{
"id": 99960,
"candidate": {
"data": {
"id": 125274,
"firstName": "CHRISTIAN",
"lastName": "NEILS"
}
},
"dateAdded": 1667986477133
},
{
"id": 99958,
"candidate": {
"data": {
"id": 125275,
"firstName": "Jose",
"lastName": "Zayas"
}
},
"dateAdded": 1667985600420
}
]
JSON;
$candidatePersonality = $exits = [];
$json = json_decode($arr,true);
array_walk($json,function($item,$key) use(&$candidatePersonality,&$exits){
$userKey = $item['candidate']['data']['firstName'].' '.$item['candidate']['data']['lastName'];
if(!isset($candidatePersonality[$userKey]) || (isset($candidatePersonality[$userKey]) && !in_array( $item['candidate']['data']['id'],$candidatePersonality[$userKey]))){
$candidatePersonality[$userKey][] = $item['candidate']['data']['id'];
if(count($candidatePersonality[$userKey])> 1){
$exits[$userKey] = $candidatePersonality[$userKey];
}
}
});
echo '<pre>';
print_r($exits);
I am new to PHP programming and I need your lights!
I have a JSON file like:
"data": [{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": 1,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": 2,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": 3,
"VALUE": "327.67"
}]
and I have to change it using another json file which is like:
"diagnostics_keys": [
{
"ID": 1,
"type": "BTTPV",
"key": "0_193_bttpv",
"unit": "V"
},
{
"ID": 2,
"type": "BTTPC",
"key": "0_195_bttpc",
"unit": "A"
},
{
"ID": 3,
"type": "AVGKMKWH",
"key": "0_202_avgkmKwh",
"unit": "Km/Kwh"
}]
How can I combine these two (using the ID and type keys/values of the second json and replace the DIAGNOSTIC_TYPE_ID with those on first json)and take a result like the bellow json?
"data": [{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPV,
"VALUE": "288.0"
},
{
"DIAGNOSTIC_TYPE_ID": BTTPC,
"VALUE": "-0.1"
},
{
"DIAGNOSTIC_TYPE_ID": AVGKMKWH,
"VALUE": "327.67"
}]
Would anyone have any points or links that may know and may help?
//change to arrays
$data = json_decode(YOUR_DATA_JSON, true); // I don't know your json variable names, so replace them
$diagnosticKeys = json_decode(YOUR_DIAGNOSTIC_KEYS_JSON, true);
//iterate over data, this is the one you want to change
foreach ($data as &$dataItem) {//(& is for replacing the values)
//another foreach for diagnostic keys
foreach ($diagnosticKeys as $diagnosticKey) {
if ($dataItem["DIAGNOSTIC_TYPE_ID"] == $diagnosticKey["ID"] {
$dataItem["DIAGNOSTIC_TYPE_ID"] = $diagnosticKey["type"];
}
}
}
//change to json again
$data = json_encode($data);
Not tested but should work.
$data1 = json_decode($json1);
$data2 = json_decode($json2);
$result = [];
foreach ($data1->data as $key => $value) {
foreach($data2->diagnostics_keys as $i => $val){
if($value->DIAGNOSTIC_TYPE_ID==$val->ID){
$value->DIAGNOSTIC_TYPE_ID = $val->type;
$result[$key]['DIAGNOSTIC_TYPE_ID'] = $val->type;
$result[$key]['VALUE'] = $value->VALUE;
}
}
}
echo json_encode($result);
I have a json data generated with the following php code
$index = array();
foreach($rows as $row)
{
$row['data'] []= (object) [];
$index[$row['cat_id']] = $row;
}
// build the tree
foreach($index as $id => &$row)
{
if ($id === 0) continue;
$parent = $row['parent'];
$index [$parent]['children'][] = &$row;
}
unset($row);
// obtain root node
$index = $index[0]['children'][0];
$json_data = json_encode($index, JSON_PRETTY_PRINT);
which produces the following json
{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}
what i want is the output to be like this
var something = [{
"cat_id": "1",
"id": "RT",
"name": "root",
"parent": "0",
"url": "www.test.com",
"data": [
{}
],
"children": [
{
"cat_id": "4",
"id": "CI.001",
"name": "Test2",
"parent": "2",
"url": "www.test.com",
"data": [
{}
]
}];
I have looked through the web with some suggesting that it is not json but php array i'm new to json. How can I solve this ?
Here is is my solution at the moment.
ob_start();
echo "var javascript_array = [". $json_data . "];\n";
$content = ob_get_contents();
file_put_contents('../core/json/tree.js', $content);
Any suggestions and improvements will be appreciated.
I am working on fetching JSON file from the database, which has two table semone with attributes id, semester, cname and table courses with attributes coname and credit.
Code I am writing in php is following.
main.php
<?php
$user = "root";
$password = "";
$database = "scheduler";
$con = mysqli_connect("localhost", $user, $password, $database) or die ("Unable to connect");
$query = "SELECT semone.userid AS id, semone.semester AS semester, semone.cname AS name, courses.credit AS value
FROM semone
INNER JOIN courses
ON semone.cname = courses.coname" ;
$result = mysqli_query($con,$query)or die ("Unable to connect");
$info = array();
$test = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['xyz'] = array(
'name'=> $row['name'],
'value'=> $row['value']
);
$info[$row['id']]['children'][$row['semester']]['children'][]= $row['xyz'];
}
$data = json_encode(($info));
echo $data;
?>
I want to get JSON file as seen in the following code, but I am getting something like this.
output.json
{
"12345": {
"children": {
"first": {
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
},
"second": {
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
},
"third": {
"children": [{
"name": "C106",
"value": 50
}]
}
}
}
}
But this is what I am expecting.
expected.json
{
"id": 12345,
"children": [{
"semester": "first",
"children": [{
"name": "C101",
"value": 100
},
{
"name": "C102",
"value": 100
}]
}, {
"semester": "second",
"children": [{
"name": "C103",
"value": 50
}, {
"name": "C104",
"value": 100
}, {
"name": "C105",
"value": 100
}]
}, {
"semester": "third",
"children": [{
"name": "C106",
"value": 50
}]
}
}
You probably should build your array in a different way:
$info[] = array(
array('id' => $row['id']),
'children' => array(
'semester' => $row['semester'],
'children' => $row['xyz']
)
);
I have:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
Which returns:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
But I need it to return as:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
To work with the select2 JQuery plugin, I'm working with.
the 'children' name doesn't matter, I think that's just a placeholder so it gets parsed correctly. I'm not sure how I would go about it, I've been trying str_replace() but even that hasn't been working out so great.
I would to it in 2 loops. The first one to group results by category, the 2nd one to format it to fit your needs:
$temp = array();
foreach($all as $array){
if (!isset($temp[$array['cat']])) {
$temp[$array['cat']] = array();
}
$temp[$array['cat']][] = array('id'=>$array['id'], 'type'=>$array['type']);
}
$result = array();
foreach ($temp as $key=>$value) {
$result[] = array('text'=>$key, 'children'=>$value);
}
echo json_encode($result);
This produces the following output:
[{"text":"Main","children":[{"id":1,"type":"Name0"},{"id":2,"type":"Name1"},{"id":3,"type":"Name3"},{"id":4,"type":"Name4"}]},{"text":"Secondary","children":[{"id":5,"type":"Name5"},{"id":6,"type":"Name6"},{"id":7,"type":"Name7"}]},{"text":"Other","children":[{"id":8,"type":"Name8"},{"id":9,"type":"Name9"},{"id":10,"type":"Name10"},{"id":11,"type":"Name11"}]}]