i have problem with this code. i want make the output look like this.
array(‘keyword’=>array(
0=>'url1',
1=>'url2',
))
currently this is my code. it only show me one url but actually theres a lot more. can someone please help me.
$data = array();
foreach ($response->Items->Item as $row)
{
$data[$keyword] = $row->DetailPageURL;
}
return $data;
Try with -
$data[$keyword][] = $row->DetailPageURL;
Replace with this code....
$data = array();
foreach ($response->Items->Item as $row)
{
$data[$keyword][] = $row->DetailPageURL;
}
return $data;
Related
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it
I have gone to the db and created an array of url's.
Then I go through the array and use xpath to tell me how many links there are per url.
This is where my head hurts.
I have a count for each url of the no of objects in each url. So I'm now trying to collect each of the nodevalues from part 2.
I'm obviously doing something wrong but need some guidence please
$items = array();
$query = "SELECT * FROM `urls`";
if( $result = mysqli_query($sql,$query));
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
while ($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
echo '<pre>';
print_r($items);
// $product = array();
echo $rowcount;
for ($x=0; $x<$rowcount; $x++){
$scrapeurl[$x] = $items[$x][url];
echo $scrapeurl[$x];
$xpath[$x] = new XPATH($scrapeurl[$x]);
$urls[$x] = $xpath[$x]->query("//div[#class='infodata']/strong/a[contains(#id,'test_title')]/#href");
$count[$x] = $urls[$x]->length;
$data = array();
for ($i=0; $i<$count[$x]; $i++){
$data[$i]['url'] = $urls[$x]->item($i)->nodeValue;
$data[] = $data[$i]['url'];
}
echo '<pre>';
print_r($data);
A bit late apologies but resolved the issue. Maybe too tired but came down to a couple of issues.
Don't always believe what the browser renders in the HTML. Look at the source! I found that tbody as an example is filled into HTML by Firefox at least in reality the source was different so I was never going to hit the right node.
looping within loops - to remember when in a loop sometimes you have to loop again to drill down to the right result......
$data = array();
foreach($urls as $node){
foreach($node->childNodes as $child) {
$data[] = array($child->nodeName => $child->nodeValue);
}
}
$data = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$data = iterator_to_array($data,false);
I have two json's
First one is
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]
Second one is
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]
I want to merge them and have a json like
[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number","DEFAULT_VALUE":"1521"}
,{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number","DEFAULT_VALUEE":"C1435"}]
is there a way to merge them? It is also OK for me if a stucture change in JSON is required
thanks.
Something like this should work:
json_encode(
array_merge(
json_decode($a, true),
json_decode($b, true)
)
)
or the same as one-liner:
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
array_merge in official PHP documentation
json_decode in official PHP documentation
EDIT: try adding true as second parameter to json_decode. That'll convert objects to associative arrays.
EDIT 2: try array-merge-recursive and see my comment below. Sorry have to log out now :(
This looks like a full correct solution: https://stackoverflow.com/a/20286594/1466341
Managed to throw this together. There is most likely a better solution, but this is the closest I got.
$a = '[{"COLUMN_NAME":"ORDER_NO","COLUMN_TITLE":"Order Number"},{"COLUMN_NAME":"CUSTOMER_NO","COLUMN_TITLE":"Customer Number"}]';
$b = '[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521"},{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435"}]';
$r = [];
foreach(json_decode($a, true) as $key => $array){
$r[$key] = array_merge(json_decode($b, true)[$key],$array);
}
echo json_encode($r);
returns,
[{"COLUMN_NAME":"ORDER_NO","DEFAULT_VALUE":"1521","COLUMN_TITLE":"Order Number"},
{"COLUMN_NAME":"CUSTOMER_NO","DEFAULT_VALUEE":"C1435","COLUMN_TITLE":"Customer Number"}]
This works like a charm for me
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
here is a full example
$query="SELECT * FROM `customer` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_personal_information=json_encode($rows);
//echo $json_personal_information;
$query="SELECT * FROM `doctor` where patient_id='1111118'";
$mysql_result = mysql_query($query);
$rows = array();
while($r = mysql_fetch_assoc($mysql_result)) {
$rows[] = $r;
}
$json_doctor_information=json_encode($rows);
//echo $json_doctor_information;
echo $merger=json_encode(array_merge(json_decode($json_personal_information, true),json_decode($json_doctor_information, true)));
This worked to me!
$dados1 = json_encode(array('data'=>'1'));
$dados2 = json_encode(array('data2'=>'2'));
echo json_encode(array_merge(json_decode($dados1, true),json_decode($dados2, true)));
This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.
heres the function:
http://pastebin.com/tQLjzzbH
I want it to return this:
{"years":[
{
"yName":"2011",
"yAlbums:[
{
auID:"1234",
aID:"456",
etc..
},
{
auID:"12345",
aID:"4567",
etc..
}
},
{
"yName":"2010",
"yAlbums:[
{
auID:"2234",
aID:"556",
etc..
}
}
]}
but its only returning this:
{"years":[
{"yName":"2011"},
{"yName":"2010"}]}
Been trying to get this for ages, am totally lost now. Some help would be appreciated.
Thanks.
You have read your result to the very end by
while($data2 = mysql_fetch_assoc($result))
{
$yearsArrayRaw[] = $data2['album_year'];
}
Add mysql_data_seek($result,0) before inner while, to line 36. Also, I would suggest rewriting this function to have single loop, using something like
$year_albums= array();
while ($data = mysql_fetch_assoc($result)){
if (empty($years[$data['album_year']])){
$year_albums[$data['album_year'] = array(
'yName'=>$data['album_year'],
'yAlbums'=>array()
);
}
//...album creation logic here...//
$year_albums[$data['album_year']['yAlbums'][] = $album;
}
//Converting arrays into objects
$years = array();
foreach ($year_albums as $year){
$years[] = (object)$year;
}
json_encode($years);