I am currently building a table that stores data it receives from an api endpoint via url. I want to add additional columns from a different endpoint. The Data is stored in JSON format and the two datasets have one key in common that is the item name.
I cant think of a way to merge these two datasets by their related key. I just started coding like a month ago. Do I need to build a database that stores the data or can i do it with php? I expirimented with mySQL but i couldent find a way to load the data from the url into my database.
Thank you very much for your help!
So i pretent to have the following data in base.json
[{ "id": 4, "name": "james" }, { "id": 6, "name": "tim" }]
and in 2nd.json
{ "4": ["flower", "car"], "6": ["house", "server"] }
so now the following PHP-Code will merge them
<?php
$api_endpoint = json_decode(file_get_contents('base.json'), true);
$additional = json_decode(file_get_contents('2nd.json'), true);
$merged_data = array();
foreach ($api_endpoint as $data) {
$merged_data[] = array_merge($data, $additional[$data['id']]);
}
var_dump($merged_data);
The Result would look like this:
["0"] => Array(
["id"] => int(4)
["name"] => str("james")
["0"] => str("flower")
["1"] => str("car")
)
["1"] => Array(
["id"] => int(6)
["name"] => str("tim")
["0"] => str("house")
["1"] => str("server")
)
So now you could use the $merged_data and insert it into your database.
Related
I have to send some data in the below format-
$postData = [
'certExpiryDate' => $certExpiryDate,
'certType' => 'SSL',
'AltName' => [
$altName[0],$altName[1]
],
'csr' => $csr
];
$altName is an array that has 2 or more strings like- domain1.com, domain2.com.
The AltName parameter expects the data in this format-
'AltName' => [
'domain1.com','domain2.com'
],
(if I hardcode and send it like this, everything works fine.. this is the correct format)
If I take the array $altName directly like this-
'AltName' => [
$altName
],
I did a var_dump and for this it adds quotes outside like- "domain1.com, domain2.com", which it considers wrong.
I need it to be in the format of $altName[0],$altName[1] which would be correct, but I'm struggling on how to loop through this array in case it has more values than 2 and still get it in the required format.
Your attempt:
'AltName' => [
$altName
],
doesn't work as intended because it wraps the array $altName inside another array (created by the [ and ]).
Just set the $altName array to be the value of the property directly. There's no need for an extra array:
'AltName' => $altName
Demo: http://sandbox.onlinephpfunctions.com/code/fa3dd6a974be7ced4bdc5d878f692549b96e2b95
but I'm struggling on how to loop through this array in case it has
more values than 2 and still get it in the required format.
posting direct values:
//$altName = ["domain1.com", "domain2.com"];
//OR
$altName = array("domain1.com", "domain2.com");
$postData = ['AltName' => $altName];
var_dump($postData);
output:
array(1) {
["AltName"]=>
array(2) {
[0]=>
string(11) "domain1.com"
[1]=>
string(11) "domain2.com"
}
}
I know how to decode a JSON string and get the data from one dimensional array but how to get the data from the nested array?
Below is my code:
$data = json_decode($json);
and below is the JSON return value:
{
"area_metadata": [
{
"name": "A",
"label_location": {
"latitude": 1,
"longitude": 1
}
},
{
"name": "B",
"label_location": {
"latitude": 1,
"longitude": 1
}
}
],
"items": [
{
"update_timestamp": "2017-05-02T09:51:20+08:00",
"timestamp": "2017-05-02T09:31:00+08:00",
},
"locations": [
{
"area": "A",
"weather": "Showers"
},
{
"area": "B",
"weather": "Cloudy"
}
]
}
]}
I had tested:
echo $data->items->locations[0]->area;
but I got this error
Trying to get property of non-object
Also,I tried to convert JSON into array instead of object:
$data = json_decode($json,true);
if (isset($data))
{
foreach ($data->items->locations as $location)
{
if (empty($location["area"])) { continue; }
if ($location["area"] == "A")
{
echo $location["weather"];
}
}
}
but it also not working.
Could anyone can advise which step that I did wrongly?
Thanks!
Edited:
Below is the pastebin link with full JSON content.
https://pastebin.com/cewszSZD
The JSON you provided (in your question) is malformed and using json_decode() on it will result in NULL. Thus nothing will happen when you try to access the decoded object because it doesn't exist.
The full JSON you provided is valid and the reason why your code didn't yield any results is because in items there is an "inner"-array:
(...)
["items"] => array(1) {
[0] => array(4) {
// ^^^^^^^^^^^^^^^^^
["update_timestamp"] => string(25) "2017-05-02T09:21:18+08:00"
["timestamp"] => string(25) "2017-05-02T09:07:00+08:00"
["valid_period"] => array(2) {
["start"] => string(25) "2017-05-02T09:00:00+08:00"
["end"] => string(25) "2017-05-02T11:00:00+08:00"
}
["forecasts"] => array(47) {
[0] => array(2) {
["area"] => string(10) "Ang Mo Kio"
["forecast"] => string(19) "Partly Cloudy (Day)"
}
(...)
You'll have to access that array through key 0, for arrays it will look like this:
$data = json_decode($json, true);
echo $data['items'][0]['forecasts'][0]['area'];
// ^^^
And for objects like this:
$data = json_decode($json);
echo $data->items[0]->forecasts[0]->area;
// ^^^
The second 0 changes the location (the different arrays in the forecasts array).
You can check the output here (array approach) and here (object approach).
It would be easier to help if you post all the JSON data or link to a screenshot of it. Try:
$items[0]['locations'][0]['area'];
Single quotes on strings, no quotes on numbers.
We have created a new db schema for old application, which currently has 4375987 rows in a single table with multiple columns. i have to migrate old data to new db schema which will fetch data from one table and be going to insert in multiple db tables.
i need to know the best approaches. should i right down the script in PHP or and other solution. the old db has very large data.
please guide thanks.
Split your row up using a function. Then take each part of the returned result and do your inserts:
See https://3v4l.org/HEFS3
<?php
$old = [
'name' => 'Dave',
'dob' => '1970-01-01',
'blah' => 'blah',
];
function convertRow($row)
{
$new = [
'table1' => [
'name' => $row['name'],
'dob' => $row['dob'],
],
'table2' => [
'blah' => $row['blah'],
],
];
return $new;
}
$data = convertRow($old);
// Now do your inserts
$firstTableData = $data['table1'];
$secondTableData = $data['table2'];
var_dump($firstTableData, $secondTableData);
This outputs:
array(2) { ["name"]=> string(4) "Dave" ["dob"]=> string(10) "1970-01-01" }
array(1) { ["blah"]=> string(4) "blah" }
So you can now take that data and do your inserts for each table. Hopefully this should get you going! :-)
I have a multidimensional array with a race type column and a boats column (which has the total number of boats for each race type). This is how I am getting the array values:
$boats = $wpdb->get_results("
select rt.race_type
,sum(tr.boat_count) boats
from registrations tr
group by rt.race_type;
");
The array works perfectly fine. But now I am trying to get the total number of boats for all race types (without using a loop). After some research, I have tried the code below, but it doesn't seem to be working:
$totalboats = array_sum(array_column($boats,'boats'));
When I run the following command:
echo $totalboats;
The result of that is 0, which is clearly wrong.
Any ideas? I am running PHP 5.6.29.
================== EDIT 01 ==================
As requested, here is the var_dump of $boats:
array(2) {
[0]=>
object(stdClass)#672 (2) {
["race_type"]=> string(12) "Elite 8-Hour"
["boats"]=> string(1) "2"
}
[1]=>
object(stdClass)#673 (2) {
["race_type"]=> string(12) "Sport 4-Hour"
["boats"]=> string(1) "2"
}
}
The problem is that your $boats sub-elements are objects and not arrays. array_column doesn't work with objects in PHP5 (it does in PHP7, though).
You could use a workaround using array_map, as shown in this answer to a previous question :
$totalboats = array_sum(
array_column(
array_map(
function($o){
return (array)$o;
},
$boats),
'boats')
);
echo $totalboats; // echoes "4"
If your variable is array and not object you can use this
$array = [
0 => [
'race_type' => 'Elite 8-Hour',
'boats' => '2',
],
1 => [
'race_type' => 'Sport 4-Hour',
'boats' => '2',
]
];
$toSum = array_sum(array_column($array, 'boats'));
echo "<pre>";print_r($toSum);die;
I am making a blogging site so I am using MongoDB as my DB. In my collection "articles", I have 1 embedded doc named posts and I want to insert 1 more embedded doc. comments into it.
DB:
{
"_id": ObjectId("4f41a5c7c32810e404000000"),
"username":"abc",
"posts": [
{
"_id": 1,
"content": "dskcnkdcnksldcnskcd",
"title" : "test1"
},
{"_id": 2,
"content": "dskcsdsl;d,cl;sdcl;sdmcnkdcnksldcnskcd",
"title" : "test2"
},
]
}
I want to insert comments into posts.
{
"_id": ObjectId("4f41a5c7c32810e404000000"),
"username":"abc",
"posts": [
{
"_id": 1,
"content": "dskcnkdcnksldcnskcd",
"title" : "test1",
"comments":[
{
"content": "usdhcjsdcjskd",
"by" : "abc"
}
]
},
{"_id": 2,
"content": "dskcsdsl;d,cl;sdcl;sdmcnkdcnksldcnskcd",
"title" : "test2"
}
]
}
Comments is actually an embedded document of posts in your document as such you need to change your query a little to:
$collection->update(array('_id' => new MongoId($bid),'posts.id'=> $pid),array('$push' => array('posts.$.comments' => $comment)));
Try that.
Notice how I have used the positional operator? You can read more about it here: http://www.mongodb.org/display/DOCS/Updating/#Updating-The%24positionaloperator
the thing you need to be careful is your structure for first insert. For example you have some user with some lists and you want to let him to have up to 5 lists. This is how you can do it with PHP:
You need to install your mongodb extension if you do not have it in your PHP environment on your localhost server
You need to install mongodb and run it.
After all that is done you can easily do it like this:
$m = new Mongo("mongodb://localhost");
$db = $m->statistic->list;
// statistic is my database and list are collection.
$list =
array(
'_id' => 18,
'lists' =>
array(
array(
'name' => 'Magento and PHP developer',
'recipients' =>
array(
'name' => 'Kristijan Glibo',
'email' => 'glibo.kristijan#gmail.com'
),
'count' => 12345),
));
You can see here that I use some (int)18 for my _id. If you do not specify it, Mongo will generate it. I use it like this just for testing purposes. Notice here that lists are array and every list inside it are array too with their own data! My list Magento and PHP developer have data about recipients and count. Recipients also have some unique data.
Lets make first insert into our Mongodb:
$document = $db->insert($list);
If we now dump collection to check out what we saved inside of it we will get this:
NOTE: To get your collection and everything inside it you can use this code:
$documents = $db->find();
echo '<pre>';
foreach ($documents as $doc) {
var_dump($doc);
}die();
********************this is dumped data*******************
["_id"]=>
int(18)
["lists"]=>
array(3) {
[0]=>
array(3) {
["name"]=>
string(10) "Magento and PHP developer"
["recipients"]=>
array(2) {
["name"]=>
string(4) "Kristijan Glibo"
["email"]=>
string(25) "glibo.kristijan#gmail.com"
}
["count"]=>
int(12345)
}
Lets now update our user and add him more lists:
$updatelist = array('name' => 'updatelist', 'recipients' => array(),'count'=>2876);
$documentupdate = $db->
update(
array('_id'=>18),
array('$addToSet' => array('lists'=> $updatelist)));
You are telling him which object to update by selectin _id => 18 and how to update. I test this and it will add new list if that list do not exist. If exist it will skip it.
Hope this helps!