Adding multiple image urls to JSON object - php

What i am trying to do is make my JSON object the same as an already developed one, these are the displays:
Original:
{
"name": "test product",
"descriptionUrl": "https:\/\/www.site.club\/",
"images": [
"https:\/\/thesite.com\/kf\/HTB1bGBljyAKL1JjSZFoq6ygCFXa7\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB1rCK3bfJNTKJjSspoq6A6mpXaJ\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB1zWO2eGmWQ1JjSZPhq6xCJFXaa\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg",
"https:\/\/thesite.com\/kf\/HTB13sOWXoRIWKJjSZFgq6zoxXXah\/TY-Unicorn-Big-Eyes-Plush-Toys-Ty-Beanie-Boos-Kids-Lovely-Children-Gifts-Kawaii-Stuffed-Animals.jpg"
],
"priceRange": {
"minPrice": "19.99",
"maxPrice": "19.99",
"currency": "USD"
},
"descriptionHtml": "HTML code can potentially go here!",
"descriptionText": "Test product description"
}
My Attempt:
{
"name": "test product",
"descriptionUrl": "https:\/\/www.site.club\/",
"images": "https:\/\/www.site.club\/images\/img-instagram-icon.png",
"priceRange": {
"minPrice": "19.99",
"maxPrice": "19.99",
"currency": "USD"
},
"descriptionHtml": "HTML code can potentially go here!",
"descriptionText": "Test product description"
}
The code i have written so far is:
<?php
if (isset($_POST['submitNewProduct'])) {
// TRY/CATCH //
try {
// 1 - PRICE ARRAY //
$prices = [];
foreach (['minPrice', 'maxPrice'] as $searchField) {
$prices[$searchField] = $_POST['product_price'];
}
$prices['currency'] = 'USD';
// 2 - IMAGES ARRAY //
$images = [];
$images = "https://www.site.club/images/img-header-39847.png";
$images = "https://www.site.club/images/img-instagram-icon.png";
// SETUP THE JSON OBJECT //
$productData = array('name' => $_POST['product_name'],
'descriptionUrl' => getUrl(),
'images' => $images,
'priceRange' => $prices,
'descriptionHtml' => 'HTML code can potentially go here!',
'descriptionText' => $_POST['product_description']
);
print_r($productData);
// INSERTION //
$i = DB::getInstance()->insert(
'products',
[
'product_unique_id' => generateId("wlu", $member),
'product_category_id' => 0,
'product_name' => $_POST['product_name'],
'product_json_body' => json_encode($productData, JSON_PRETTY_PRINT),
'product_url' => getUrl(),
'product_active' => 'Y',
'product_date' => date('Y-m-d H:i:s')
]);
stdmsg("...");
} catch (Exception $e) {
stderr($e->getMessage());
}
}
?>
The issue is when i'm adding images, in the original JSON object, it is displayed between the [ ] square brackets, also in my test above i cannot add multiple images to the JSON object like the original format, any help would be appreciated.

In this line
$images = "https:... ";
you are overwriting the array $images you've defined just before.
You want to add, so you've got the choice of doing
$images[] = "https:....";
or
array_push($images, "https://www...");
or already add the strings when creating the array:
// images = []; // not needed then!
$images = ["https:..firstimage..", "https:secondimage"];

After declaring image array, accidently you are over writing it you should assigen image names on different different indexes like
$images[0] = "string image name" and so on..
or use array_push method to push entries in images variavle which is an array.
Hope it will work.

Related

Create a JSON tree view in PHP using delimiter

I am trying to create a file explorer type treeview JSON to be read by FancyTree for a project I'm attempting.
The files are stored in a database, with an ID, name, URL, Type and code fields. The mock database looks like this:
ID name URL. Type code
1 test dir.dir1 txt sometext
2 next dir.dir1 txt somemoretext
3 main dir txt evenmoretext
I need to build the JSON tree view from this data, using the URL as a path (period being the delimiter) and the files being inside the final directory so the tree looks like
/dir/dir1/test.txt
/dir/dir1/next.txt
/dir/main.txt
FancyTree JSON output should look like
[
{
"title": "dir",
"folder": true,
"children": [
{
"title": "dir1",
"folder": true,
"children": [
{
"title": "test.txt",
"key": 1
}, {
"title": "next.txt",
"key": 2
}
]
}, {
"title": "main.txt",
"key": 3
}
]
}
]
Currently, I'm getting the data from the database into $scriptArray
SELECT 'name','url','type','id' FROM.....
I'm then sorting and building a tree with
$url = array_column($scriptArray, 'url');
array_multisort($url, SORT_ASC, $scriptArray);
$result = [];
foreach($scriptArray as $item) {
$loop = 0;
$keys = array_reverse(explode('.', $item->url));
$tmp = $item->name;
$tmp2 = $item->type;
foreach ($keys as $keyid => $key) {
if($loop == 0) {
$tmp = ["title" => $tmp.".".$tmp2, 'key' => $item->id];
} else {
$tmp = ["title" => $keys[$keyid - 1], "folder" => true, "children" => [$tmp]];
}
$loop++;
}
$tmp = ["title" => $keys[count($keys)-1], "folder" => true, "children" => [$tmp]];
$result[] = $tmp;
}
However, the output I'm getting is.
[
{
"title": "dir",
"folder": true,
"children": [
{
"title": "dir2",
"folder": true,
"children": [
{
"title": "test.txt",
"key": 1
}
]
}
]
},
{
"title": "dir",
"folder": true,
"children": [
{
"title": "dir2",
"folder": true,
"children": [
{
"title": "next.txt",
"key": 2
}
]
}
]
},
{
"title": "main.txt",
"key": 3
}
]
I have tried applying an array_merge, array_merge_recursive and various others without success. Can anyone help with this?
Working with loop won't work unless you know per advance the maximum depth of your folder hierarchy.
A better solution is to build the folder path "recursively", and append the file to the final folder.
This can be achieved with by creating a reference with the & operator, and navigate to its children until the whole path is build :
$result = array();
foreach($files as $file)
{
// build the directory path if needed
$directories = explode('.', $file->url); // get hierarchy of directories
$currentRoot = &$result ; // set the pointer to the root directory per default
foreach($directories as $directory)
{
// check if directory already exists in the hierarchy
$dir = null ;
foreach($currentRoot as $i => $d)
{
if(isset($d['folder']) && $d['folder'] and $d['title'] == $directory)
{
$dir = &$currentRoot[$i] ;
break ;
}
}
// create directory if missing
if(is_null($dir))
{
$item = array(
'title' => $directory,
'folder' => true,
'children' => array()
);
$currentRoot[] = $item ;
$dir = &$currentRoot[count($currentRoot)-1];
}
// move to the next level
$currentRoot = &$dir['children'] ;
unset($dir);
}
// finally append the file in the latest directory
$currentRoot[] = array(
'title' => $file->name . '.' . $file->type,
'key' => $file->id,
);
unset($currentRoot);
}
echo json_encode($result);

create embedded json for autocomplete

I am using following code for making data coming from database as json format
public function employeeSearch()
{
$arrayOfEmployee = array();
$arrayToPush = array();
$arrayToJSON = array();
$new_item = $this->apicaller->sendRequest(array(
"controller" => "Employee",
"action" => "employeeSearch",
"searchCriteria" => "12345"
));
$arrayOfEmployee = json_decode($new_item,true);
foreach($arrayOfEmployee as $key => $employee)
{
$arrayToPush = array('data' => $employee['FullName'], 'value' => $employee['_id']['$oid']);
array_push($arrayToJSON, $arrayToPush);
}
echo json_encode($arrayToJSON);
}
The output is
[{"data":"Aasiya Rashid Khan","value":"5aa662b0d2ccda095400022f"},
{"data":"Sana Jeelani Khan","value":"5aa75d8fd2ccda0fa0006187"},
{"data":"Asad Hussain Khan","value":"5aaa51ead2ccda0860002692"},
{"data":"Ayesha Khan Khann","value":"5aab61b4d2ccda0bc400190f"},
{"data":"adhar card name","value":"5aaba0e1d2ccda0bc4001910"}
]
Now I want that json elements should look like
{
"suggestions": [
{
"value": "Guilherand-Granges",
"data": "750"
},
{
"value": "Paris 01",
"data": "750"
}
]
}
I have to implement this in jQuery autocomplete plugin...
Please help!!!
Replace the last line with
echo json_encode(["suggestions" => $arrayToJSON]);
This should result in the wanted result!
(This hold only true if you igonre the fact that the data in value and name is not the same/similar)

Create 2D-Array from mysql query in php

I have this following result in my query:
I'm trying to create an array like this in php:
[
{
"software_version": "1.0",
"version_date": "10/08/2016",
"changelog": [
{
"type": "IMP",
"description": "Initial version."
}
]
},
{
"software_version": "1.0.1",
"version_date": "27/07/2017",
"changelog": [
{
"type": "ADD",
"description": "HostPanel update manager."
},
{
"type": "ADD",
"description": "Hook OnDaemonMinute."
}
]
}
]
I need to combine the result with the software_version row.
Any help is appreciated.
My php code:
$changelog = array();
foreach ($result as $r) {
$changelog[] = array(
'software_version' => $r['software_version'],
'version_date' => $r['version_date'],
'changelog' => array(
array(
'type' => 'IMP', // help
'description' => 'Initial version.'
)
)
);
}
The key is to use the software version as a key in $changelog as you build it.
$changelog = array();
foreach ($result as $r) {
// get the version (just to make the following code more readable)
$v = $r['software_version'];
// create the initial entry for the version if it doesn't exist yet
if (!isset($changelog[$v]) {
$changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']];
}
// create an entry for the type/description pair
$change = ['type' => $r['type'], 'description' => $r['description']];
// add it to the changelog for that version
$changelog[$v]['changelog'][] = $change;
}
You'll need to use array_values to reindex $changelog before JSON encoding it in order to produce the JSON array output you're going for.
$changelog = array_values($changelog);

Convert PHP array to JSON using multi dimentional arrays

I am trying to convert this php array to a json. This is my code:
$c = array();
$c = array(
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
),
);
$json = json_encode($c);
echo $json;
This is the output I'd like to acieve:
{"cronjobs":[{"id":1186437,"groupId":12379]}
Though using the above code this is what I am getting
[{"id":1189515,"groupId":12379}]
The [{"cronjobs"part is not appearing.
I'm not sure what I'm doing wrong.
This should get the result that you want (just wrap an array around the id, groupId array):
<?php
$c = array();
$c['cronjobs'] = array(array(
'id'=>1189515,
'groupId'=>12379,
));
echo json_encode($c);
// result {"cronjobs":[{"id":1189515,"groupId":12379}]}
?>
This is how you need to format your array:
$c = array(); // declare the array
$c['cronjobs'] = array( // populate the array
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c); // json_encode it
echo $json;
There is no need for $c = array($c['cronjob']); (which was what you were doing).
I think this is what you're looking for:
$c = array('cronjobs' => array());
$c['cronjobs'][] = array('id' => 1189515, 'groupId' => 12379);
//$c['cronjobs'][] = array('id' => 1234, 'groupId' => 4321);
$json = json_encode($c);
echo $json;
Cronjobs needs to contain an array of cronjob objects/arrays
Could also be written using one statement, like this:
$c = array('cronjobs' => array(
array('id' => 1189515, 'groupId' => 12379),
array('id' => 1234, 'groupId' => 4321)
));
Your problem is that in PHP array is used to represent both JSON objects and JSON lists hence the confusion. Consider the following code:
$cronjob = array(
'id' => 1189515,
'groupId' => 12379
);
echo json_encode($cronjob);
// {"id":1189515,"groupID":12379"}
As you can see this represents a single object. So we'll create a list of objects:
$cronjobs = array($cronjob);
echo json_encode($cronjobs);
// [{"id":1189515,"groupID":12379"}]
This is now a list as expected. Now the parent object:
$c = array(
'cronjobs' => $cronjobs
);
echo json_encode($c);
// {"cronjobs":[{"id":1189515,"groupID":12379"}]}
In JSON there is a name: value pair system
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
}
],
"children": [],
"spouse": null
}
if you want to achieve like {"cronjobs":[{"id":1186437,"groupId":12379]} then the array must be named like the following in PHP:
$c['cronjobs'] = array(
'id'=>1189515,
'groupId'=>12379,
);
$json = json_encode($c);
echo $json;

How to format array as key : value?

I have a array like this:
Array
(
[0] => Chat Show
[1] => Non-fiction
[2] => Inspirational
)
And i am trying to get this format:
"genres": [
{
"name": "Chat Show"
},
{
"name": "Non-fiction"
},
{
"name": "Inspirational"
}
]
but i get something like this:
genres": [
"Chat Show",
"Non-fiction",
"Inspirational"
]
This is what i am doing:
while($row = mysqli_fetch_array($Data))
{
$Genres = explode('/', filter_var(rtrim($row['genres'], '/'), FILTER_SANITIZE_URL));
}
and then this is part of a bigger array
"genres" => $Genres
print_r(
json_encode(["genres" => array_map(
function($v) { return ['name' => $v]; },
$Genres)]));
result
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
For example, here is your array in PHP
$var = array(
"Chat Show",
"Non-fiction" ,
"Inspirational"
);
Without a key "name". You should create a new array and push each element as an array to your new array.
$result = array();
foreach($var as $name)
{
$arr = array("name"=>$name);
array_push($result, $arr);
}
after that, encode your $result by using json_encode
$json = json_encode($result,true);
echo $json;
Here is my output by echo $json.
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
Try this:
$Genres=array("Chat Show","Non-fiction","Non-fiction");
$new["genres"]=array();
foreach($Genres as $key => $name){
$new["genres"][$key] = ['name' => $name];
}
echo json_encode($new);
Output
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Non-fiction"}]}
The json string you posted here is not a valid json OR is part of json.
So, you might already have genres in your javascript, and want to get the remaining thing, which is
[
{ "name": "Chat Show" },
{ "name": "Non-fiction" },
{ "name": "Inspirational" }
]
Your current PHP $Genres looks like this because you are exploding the string
$Genres = [ 'Chat Show', 'Non-fiction', 'Inspirational' ];
Apply this to change values of your current $Genres
array_walk($Genres, function(&$v){ $v = ['name'=>$v]; });
Use it in your javascript like,
"genres": <?php json_encode($Genres)?>
Try this:
$genres_new['name']=$Genres;
echo json_encode($genres_new);
Your problem is, that you have simple array of strings, but you want an associative multilevel array. This is an relative simple operation. First lets illustrate the problem with some code:
// That is what you have, an :
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// or the same for php > 5.4:
$Genres = array(
"Chat Show",
"Non-fiction",
"Inspirational",
);
This will produce the following json string (echo json_encode($Genres);):
["Chat Show","Non-fiction","Inspirational"]
But if you want such an output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
You have to convert the strings into an array. You can do that with that (or a similar loop):
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
After that your array look like this:
Array (
0 =>
array (
'name' => 'Chat Show',
),
1 =>
array (
'name' => 'Non-fiction',
),
2 =>
array (
'name' => 'Inspirational',
),
)
Putting things together you will get something like that:
<?php
// Do whatever is necessary to build your Genres array ...
$Genres = [
"Chat Show",
"Non-fiction",
"Inspirational",
];
// Convert the array into an array of arrays
foreach($Genres as $key => $name){
$Genres[$key] = ['name' => $name];
}
echo json_encode($Genres);
/**
Now you will get this output:
[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]
*/
// After that you can add it to the bigger array:
$biggerArray = [];
$biggerArray['genres'] = $Genres;
echo json_encode($biggerArray);
/**
Output:
{"genres":[{"name":"Chat Show"},{"name":"Non-fiction"},{"name":"Inspirational"}]}
*/

Categories