Append Array to Output to JSON after Looping with PHP - php

Essentially, the data should look as follows, but as one array for each user that contains their info. It should be packaged as a JSON after completely looping through.
Preface
Using the pre tags with print_r I got what it should look like using some humorous sample data:
User 1 is following:
Array
(
[0] => Array
(
[first] => Hugh
[last] => Janus
[bg] => /resources/bg/2/b.png
[prof_pic] => /resources/profilepics/2/b.jpg
[bio] => 50% proctologist, 50% baker.
)
)
Array
(
[0] => Array
(
[first] => Andrew
[last] => Dickens
[bg] => /resources/bg/3.c.jpg
[prof_pic] => /resources/profilepics/3/c.jpeg
[bio] => Therapists are pretty cool.
)
)
Array
(
[0] => Array
(
[first] => Anita
[last] => Dickson
[bg] => /resources/bg/4/d.jpg
[prof_pic] => /resources/profilepics/4/d.JPG
[bio] => Just another barista.
)
)
Essentially, everything needs to come back as one JSON item that someone could use for any purpose with the supplied info.
Background on the Following Code
This code selects all User IDs from the table 'followers' where the person who is following someone is equal to fB and the person who owns that friendship is fA. In this instance, userID 1 is trying to look at a page of every person they follow with their profile pic, background pic, first name, last name, and bio. The data that the JSON is outputting will be formatted in another file, but this is just being used to curate the raw data.
$dbh is the PDO database connection and the code uses prepared statements for security.
Code
$flingJSON = 0;
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
$flingJSON = $getInfoFling->fetchAll(PDO::FETCH_ASSOC);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";
}
Your help is greatly appreciated in advance and as a thanks you'll get a shout-out in the documentation for this file.

This should return a single array with all the user's info:
//Create empty data array
$flingData = array();
$userid = "1";
$result = $dbh->prepare('SELECT fA
FROM followers
WHERE fB=:userid');
$result->bindParam(':userid', $userid);
$result->execute();
$rawData = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($rawData as $following) {
$followingID = $following['fA'];
$getInfoFling = $dbh->prepare('SELECT first, last, bg, prof_pic, bio
FROM users
WHERE id=:flingID
');
$getInfoFling->bindParam(':flingID', $followingID);
$getInfoFling->execute();
//Append user info to data array
$flingData[] = $getInfoFling->fetch(PDO::FETCH_ASSOC);
}
//Create JSON string
$flingJSON = json_encode($flingData);
echo "<pre>";
print_r($flingJSON);
echo "</pre>";

Related

PHP Multidimensional Array Merge Issue

I am running a query that outputs a multidimensional array like this: -
Array
(
[0] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
[1] => Array
(
)
[2] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
I am trying to make the Array look like this so that we can loop through it on our site: -
Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)
This is all being generated using PHP using Symfony2 and Doctrine2. I have tried a couple of methods to get this working but I have reverted back to my first method which is this: -
$companies = array();
foreach($postcodes as $key=>$value) {
$conn = $em->getConnection();
$query = $conn->prepare("SELECT a.id, a.display_name, a.profile_page, b.meta_data FROM companies a, `cms`.pages b WHERE b.slug = a.profile_page AND a.active = 1 AND a.postcode = ".$value." ORDER BY a.display_name ASC");
$execute = $query->execute();
$companies[] = array_replace_recursive($query->fetchAll());
}
echo '<pre>'; print_r($companies); echo '</pre>';
die();
If someone can show me how to get around this, that would be great.
$query->fetchAll() is itself is an multidimensional array you're in need.
Just replace following line
$companies[] = array_replace_recursive($query->fetchAll());
with
$innCompnies=$query->fetchAll();
foreach($innCompnies as $inComp) {
$companies[]=$inComp;
}
It wasn't working because you were pushing multidimensional array into another array. What we actually need to do is to push element one by one into the main array.
I suggest you to avoid SQL-queries in loop. Also you have potential SQL-injection vulnerability concatenating postcodes to your query. So the possible solution may be replacing your foreach loop with something like:
$companies = $conn->fetchAll(
"SELECT a.id, a.display_name, a.profile_page, b.meta_data FROM companies a, `cms`.pages b WHERE b.slug = a.profile_page AND a.active = 1 AND a.postcode IN :postcodes ORDER BY a.display_name ASC",
compact('postcodes')
);
you can transform the multidimentional array like this.
$new_companies = array();
array_walk($companies, function($companie) use($companies, &$new_companies){
if(is_array($companie)) {
foreach ($companie as $c) {
$new_companies[] = $c;
}
}
});
$new_companies is what you want.

PHP > How to skip an element while using json_encode

I need to send data to the client side in JSON format.
So far, it worked just fine with json_encode as follows:
$sql = "SELECT `card`.`CardID`,`card`.`Text`,... WHERE (`card`.`CardID`= :ItemId)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ItemId', $itemid);
$stmt->execute();
while ($row = $stmt->fetchObject()) {
$posts[]=$row;
}
...
...
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);
But now I have a problem. I have a new field (Videofiles) in the DB that is already JSON formatted- stored as the ouput of a SDK function. If I encode this JSON encoded field once more, I get data which is unreadable on the client side..
How can I json_encode all the other data, but skip this specific field, Videofiles?
Here is the output of a sample data structure using print_r:
Array
(
[rows] => Array
(
[0] => stdClass Object
(
[Name] => Company13
[CID] => 26
[CardID] => 26-000002
[Text] => Kleopatra Deluxe Hotel reservations
[ImageLink] =>
[VideoFiles] => [{"quality":"mobile","type":"video/mp4","width":480,"height":270....}]
[ClickDate] => 2015-11-03
)
)
[maptel] => 0
)
Thanks...
You could use json_decode to decode the already encoded field and then add the result in the $res array.
Best way to do it delete this section in SQL!
But if you want to delete in php it will have a cost for you and you can use unset for this situation;
foreach ($posts as $post){
unset($posts['VideoFiles']);
}
$res["rows"] = $posts;
$res["maptel"] = $maptelindicator;
echo json_encode($res,JSON_UNESCAPED_UNICODE);

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

Displaying the BLOB file on frontend using PHP

I have a table named listing_fees
and I want to get the data by the id of 12
the data that I want to get is a BLOB that is named [BLOB - 205B]
inside the BLOB file is an array like this:
a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}
I don't understand a thing on this code.
I want to display it on the frontend of my html using PHP
what will I to display it?
SQL Query or something else.
That data is in PHP Serialized format you can decode it using unserialize
Example
$data = 'a:7:{s:2:"id";s:1:"1";s:5:"label";s:8:"For Sale";s:6:"amount";s:4:"0.00";s:4:"days";s:1:"7";s:6:"images";s:1:"0";s:10:"categories";a:2:{s:3:"all";i:0;s:10:"categories";a:1:{i:0;i:30;}}s:10:"extra_data";N;}';
$data = unserialize($data);
echo "<pre>" ;
foreach ( $data as $key => $value ) {
if ($key == 'categories') {
echo $key, " = ", $value['categories']['0'], PHP_EOL;
} else {
echo $key, " = ", $value , PHP_EOL;
}
}
Output
id = 1
label = For Sale
amount = 0.00
days = 7
images = 0
categories = 30
extra_data =
The data in the BLOB column appears to be serialized data, not a file. Because of this, you don't want to just "output" it to the page - you'll want to unserialize it (via PHP's unserialize() method) and then process to be displayed, well, however it should be displayed. Taking the exact data you display in your question and passing using unserialize() on it gives me an array with the following:
Array
(
[id] => 1
[label] => For Sale
[amount] => 0.00
[days] => 7
[images] => 0
[categories] => Array
(
[all] => 0
[categories] => Array
(
[0] => 30
)
)
[extra_data] =>
)
A simple setup, to query the database and retrieve the column, would be:
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
$result = $mysqli->query('SELECT column_name FROM listing_fees WHERE id = 12');
$data = $result->fetch_assoc();
$result->close();
To use the data that is in the $data array, you can do:
$blob = unserialize($data['column_name']);
Now, you can display the data however you want, accessing each value with $blob['label'] or $blob['days'].

PHP - Removing one array layer

I have a simple PHP function that will grab information from a database based on a unique ID:
function oracleGetGata($query, $id="id") {
global $conn;
$results = array();
$sql = OCI_Parse($conn, $query);
OCI_Execute($sql);
while ( false!==($row=oci_fetch_assoc($sql)) ) {
$results[ $row[$id] ] = $row;
}
return $results;
}
So for example $array = oracleGetData('select * from table') would return:
[1] => Array
(
[Title] => Title 1
[Description] => Description 1
)
[2] => Array
(
[Title] => Title 2
[Description] => Description 2
)
This is fine, however, if I just want to return one record $array = oracleGetData('select * from table where id = 1') it returns the data like:
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
Not only am I unsure of how to reference this (there is nothing identifying the array) I'd also like to somehow change my function so if it just returns one record, it will just be a simple one dimensional array.
I've looked into the usual PHP array functions but can't find anything that'll help, nor an easy way of identifying how deep the array is.
Would really appreciate any help, thank you
Use array_pop():
$array = array_pop(oracleGetData('select * from table where id = 1'));
You will then get one single array:
Array
(
[Title] => Title 1
[Description] => Description 1
)
Instead of an array embedded in another one:
Array
(
[] => Array
(
[Title] => Title 1
[Description] => Description 1
)
}
I think there is an logic error in your script:
Change
$results[ $row[$id] ] = $row;
into
$results[] = $row;
The problem is, that you want to have the Database key value as array key value, but you don't know the Database key, since you don't know what the query will look like.
You could try:
$results[$row['id']] = $row;
But this only works when all of your results have a Database key named "id".
You pass a $id in the function signature, but in the loop you uses $row[$id], Why? Maybe the error is there.
If you want a sequencial id in your result set, you don't need use the $id, you can uses array_push() function
array_push($result, $row);
OR
$results[] = $row;

Categories