How I coul get a JSON like this? - php

I need to get a JSON with arrays, how I could do it?
//JSON I need to get
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}
//For now, I got this
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
function Keywords($keywords, $tags){
$fields= array("keywords" => $keywords);
$jsondata = json_encode($fields);
print_r($jsondata );
}
//output
{"keywords":["kw1","kw2"]}
I expect the output like this:
{"keywords":[{"keyword":"kw1", "tags":["sample"]},{"keyword":"kw2", "tags":["sample, sample2"]}]}

Assuming tags in the first element of your example is supposed to be ["sample, sample2"] as well (otherwise you would really have to explain by what logic you want to achieve at the result as shown) …
$keywords = array("kw1", "kw2");
$tags= array("sample", "sample2");
$result = new StdClass;
$result->keywords = [];
foreach($keywords as $keyword) {
$temp = new StdClass;
$temp->keyword = $keyword;
$temp->tags = [];
foreach($tags as $tag) {
$temp->tags[] = $tag;
}
$result->keywords[] = $temp;
}
echo json_encode($result);
Basically two nested loops over the keywords and the tags, and inside a new temporary object is created an then appended to the result array.

Related

Concatenate JSON in php with read Database

I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);

looping through xpath results

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);

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

How do i merge matching strings in an array?

Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.
function get_tags()
{
$tag_array = array();
$query = mysql_query("
SELECT tags
FROM gallery_image
");
while($row = mysql_fetch_assoc($query))
{
$tags = $row['tags'];
$tag_array[] = $tags;
}
echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
You question is not very clear but array_unique may be what you need?
function get_tags()
{
$query = mysql_query('SELECT tags '.
'FROM gallery_image');
$tag_array = array();
while($row = mysql_fetch_assoc($query))
$tag_array = array_merge($tag_array, explode(',', $row['tags']));
return array_unique($tag_array);
}
You probably want something like this:
$tags = array(
'one,two',
'one,three',
);
$result = array_unique(array_reduce($tags,
function($curr, $el) {
return array_merge($curr, explode(',', $el));
},
array()));
See it in action.
What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.
Try this:
$unique_tags = array();
foreach ($tag_array as $value) {
$unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);

building an associative array

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.

Categories