I got a little lazy and just used PHP to store all these values, I should be using Javascript to do this though. Whats the best way to do the following in Javascript? I would then be using jQuery's .each function to loop through it.
$accessories = array (
array('name' => 'Chrome pull out wire Basket 500 & 600 wide ', 'price' => '60'),
array('name' => 'Chrome shoe rack 2 Tier', 'price' => '95'),
array('name' => 'Chrome Shoe Rack 3 Tier', 'price' => '145'),
array('name' => 'Chrome pull out trouser rack', 'price' => '40'),
array('name' => 'Pull out tie rack', 'price' => '135'),
array('name' => 'Pull Down hanging Rail 450mm to 1190mm width', 'price' => '33.50'),
array('name' => 'Corner Hanging Rail', 'price' => '33.50')
);
JavaScript doesn't have associative arrays, so you'd have to build it as a series of objects in an array.
var accessories = [
{ 'name' : 'Chrome pull out...', 'price' : 60 },
{ 'name' : 'Chrome shoe rack..', 'price' : 95 }
];
You could then cycle over it using $.each as you requested:
$.each( accessories, function(){
alert( this.name );
});
Fiddle: http://jsfiddle.net/jonathansampson/HXwMc/
Quickly Convert PHP Array to JSON
You can get the above structure easily by passing the array through json_encode():
echo json_encode( $accessories );
It would probably look like this:
var array = [
{"name": "Chrome pull out wire Basket 500 & 600 wide ", "price": "60"},
{"name": "Chrome shoe rack 2 Tier", "price": "95"},
{"name": "Chrome Shoe Rack 3 Tier", "price": "145"},
{"name": "Chrome pull out trouser rack", "price": "40"},
{"name": "Pull out tie rack", "price": "135"},
{"name": "Pull Down hanging Rail 450mm to 1190mm width", "price": "33.50"},
{"name": "Corner Hanging Rail", "price": "33.50"}
];
Note that this is an array of objects. JavaScript doesn't have associative arrays, those are objects.
As Jonathan noted, that's an array of objects in Javascript. It would look like this
var accessories = [
{
name: 'hello',
price: 1.00,
},
{
name: 'world',
price: 2.50,
}
]
Related
This is a sample of data I get from user choices:
id:1,
title: 'foam',
add:'dry',
id:2,
title: 'flavor',
add:'milk'
id:3,
title: 'heat',
add:'hot'
id:1,
title: 'rost',
add:'robosta'
I want to put and sync each title based on user choices: I mean a user can select among 'flavor' title adds like 'milk', 'coconut' or 'banana', and so on.
I use this code but only update one title and the selected choice:
public function add($variation, $id, $title, $add, $quantity = 1)
{
$this->cart->variations()->syncWithoutDetaching([
$variation => [
'quantity' => quantity,
'toppings' => [['id'=> $id], 'title' => $title, 'add' => $add]],
]
]);
}
then I have this result:
[{"id":2," title": "flavor", "add": "milk"}]
while I need:
[{"id": "1", "title": "Flavour", "add": "Milk"},{"id": "2", "title": "Foam", "adds": "Dry"},{"id": "3", "title": "Heat", "adds": "Cold"},{"id": "4", "title": "Roast", "adds": "Robosta"}]
I added id to JSON to sync.
how I can sync or update the selected title and its add?
i done search tutorial for send post json with curl ..
but for this value i cant find in here..
and my question how to convert to array post json in value if like
this, and this my value post json
{
"payment_type": "bca_klikpay",
"transaction_details": {
"order_id": "orderid-01",
"gross_amount": 11000
},
"item_details": [
{
"id": "1",
"price": 11000,
"quantity": 1,
"name": "Mobil "
}
],
"customer_details":{
"first_name": "John",
"last_name": "Baker",
"email": "john.baker#email.com",
"phone": "08123456789"
},
"bca_klikpay": {
"description": "Pembelian Barang"
}
}
i done try to php array like this but still error
$item = array('id' => 'id1', 'price' => 11000, 'quantity' => 1 , 'name' => 'Mobil');
$data2 =array('payment_type' => 'bca_klikpay',
'transaction_details' => array('order_id' => 'orderid-01', 'gross_amount' => 11000),
'item_details' => array([$item]),
'customer_details'=> array('first_name' => 'john',
'last_name' => 'baker', 'email' => 'john.baker#email.com', 'phone' => 08123456789),
'bca_klikpay' => array('description' => 'Pembelian Barang'));
maybe someone can help me.. and sory for my bad english
thanks
There is the following error - the phone number has to be string, not number, so it would look like this 'phone' => '08123456789', because numbers cannot begin with 0.
Beside this, there is the following issue - You should not set item_details like this, but rather 'item_details' => [$item]. You do not need 2 nested arrays, just one. (array() is equal to []. They are practically the same in your use case. So you are doing something like array(array($item)), which is wrong)
What else, you have to do a $json = json_encode($data2); at the end and it will return what you want it to.
I am rather new to PHP so I don't know how to work with these datasets. I make a MySQL select and get back an object like this:
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 1,
"dailyworkhourssum": "7.70"
},
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 3,
"dailyworkhourssum": "1.2"
},
{
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": "7.70"
},
I want to iterate through this and in the end it should look like this:
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid1": true,
"categorid3": true,
"dailyworkhourssum1": "7.70",
"dailyworkhourssum3": "1.2"
},
{
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": "7.70"
},
What this does is that it merges tow fields together (if they have the same bookingdate )into one so that I can display it in a table without reoccurring dates.
My problem:
I don't know what this type of data is called.
I don't know how to create something like this.
I can add fields to this type of data with $data->newField = example so I think that this is an object.
In JS it's called an object, but in PHP you will use an associative array instead.
In your case, I think, you have an array of associative arrays. It looks like this:
$books = [
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 1,
"dailyworkhourssum" => "7.70"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 3,
"dailyworkhourssum" => "1.2"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-05",
"categoryid" => 3,
"dailyworkhourssum" => "7.70"
]
];
If you wanna merge an arrays with the same "bookingdate" then I recommend you to loop through this array and add its elements to another associative array with bookingdates as keys, and check, in case if there is such key already, then merge the arrays, like this:
$merged = [];
foreach ($books as $book) {
$date = $book['bookingdate'];
if (isset($merged[$date])) {
$merged[$date] = $merged[$date] + $book;
} else {
$merged[$date] = $book;
}
}
I think that it is not a valid code (no time, sorry), but I hope, you cautch the idea.
If you want a 'list' instead of an associative array, than you can do this:
$mergedList = array_values($merged);
Thus you will rid of string keys.
If I understood correctly, you obtain a table with 4 columns an a variable number of rows and you want to transform it to a table with a variable number of columns. For that, using a data structure where every item is different from the previous one can make everything harder than it needs. I'd suggest you use a fixed structure:
// I'm assuming you have a PHP array as starting point
$input = [
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 1,
'dailyworkhourssum' => '7.70',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 3,
'dailyworkhourssum' => '1.2',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-05',
'categoryid' => 3,
'dailyworkhourssum' => '7.70',
],
];
$output = [];
foreach ($input as $data) {
// We'll group by booking date
if (!isset($output[$data['bookingdate']])) {
$output[$data['bookingdate']] = [
'membername' => $data['membername'],
'bookingdate' => $data['bookingdate'],
'categoryid' => $data['categoryid'],
'dailyworkhourssum' => [],
];
}
// A single date may have several daily work hours
$output[$data['bookingdate']]['dailyworkhourssum'][] = $data['dailyworkhourssum'];
}
// We discard array keys (we only needed them to group)
echo json_encode(array_values($output));
[{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 1,
"dailyworkhourssum": ["7.70", "1.2"]
}, {
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": ["7.70"]
}]
Wherever you consume this JSON you just need to loop the dailyworkhourssum array. You may also want to loop the entire structure before printing the table and keep a counter in order to determine the maximum number of columns so you can draw empty cells where needed (tables are rectangular).
I want to build a json request required for JIT SpaceTree.
The workflow: a question is started with the id of the retrospective answer stored.
If the option is yes then it loads the next question based on the load_yes value. this load_yes value selects the id and loads that question.
If the option is no it loads the next no based question by its id stored under load_no,
json should look like:
var json = {
id: "start",
name: "does test work?",
data: {},
children: [{
id: "layer1_1",
name: "option: no, id 3, Q: test does work with option no?",
data: {},
children: []
}, {
id: "layer1_2",
name: "option: yes, id 2, Q: test does work!!",
data: {},
children: [{
id: "layer2_1",
name: "option: no, id 4, Q: test does work?",
data: {},
children: []
}, {
id: "layer2_2",
name: "option: yes, id 5, Q: ",
data: {},
children: []
}]
}]
};
$query = $mysqli->query("SELECT * FROM topic_answer");
while($obj = $query->fetch_object()){
$arr[] = array(
'id' => $obj->id,
'name' => $obj->topic_question,
'data' => '',
'children' => array(array(
'id' => $obj->load_yes,
'name' => $obj->load_yes,
'data' => '',
'children' =>array(),
),array(
'id' => $obj->load_no,
'name' => $obj->load_no,
'data' => '',
'children' => array(),
),
)
);
id, topic_name, topic_creator, topic_question, load_yes, start, load_no, end
1 test jordan does test work? 2 1 3 0
4 test jordan test does work no 0 0 0 0
5 test jordan test does work yes 0 0 0 0
2 test jordan test does work yes!! 4 0 5 0
in json, objects are depicted as {}. so basically what this code means is an array of objects:
[
{},
{}
]
so here, where you are nesting arrays:
'children' => array(array(
'id' => $obj->load_yes,
'name' => $obj->load_yes,
'data' => '',
'children' =>array(),
),array(
'id' => $obj->load_no,
'name' => $obj->load_no,
'data' => '',
'children' => array(),
),
)
you actually want to replace the inner array by an object, such as stdClass(). stdClass is used like this:
$obj = new stdClass();
$obj->id = "layer1_1";
$obj->name = "option: no, id 3, Q: test does work with option no?";
$obj->data = new stdClass();
$obj->children = array();
then, with php
'children' => array(
$obj1,
$obj2,
),
So my code here:
$featurecollection = ("FeatureCollection");
$test[] = array (
"type" => $featurecollection,
$features[] = array($images)
);
file_put_contents($cache,json_encode($test));
results in the following json:
[
{
"type":"feature",
"0":[
[
{
"title":"some title",
"src":"value",
"lat":"value",
"lon":"value"
},
{
"title":"some title",
...
But I need to nest things differently and I'm perplexed on how the php array should be constructed in order to get a result like:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":{
"coordinates":[
-94.34885,
39.35757
],
"type":"Point"
},
"properties":{
"latitude":39.35757,
"title":"Kearney",
"id":919,
"description":"I REALLY need new #converse, lol. I've had these for three years. So #destroyed ! :( Oh well. Can't wait to get a new pair and put my #rainbow laces through. #gay #gaypride #bi #proud #pride #colors #shoes #allstar #supporting ",
"longitude":-94.34885,
"user":"trena1echo5",
"image":"http://images.instagram.com/media/2011/09/09/ddeb9bb508c94f2b8ff848a2d2cd3ece_7.jpg",
"instagram_id":211443415
}
},
What would the php array look like for that? I'm thrown off by the way everything is nested but still has a key value.
Here's how I'd represent that in PHP:
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
So to get that structure, each feature has to be an associative array of:
type,
geometry - an associative array of:
coordinates - an indexed array of values,
type
properties - an associative array of values like latitude, longitude, id etc.
It's times like these when I prefer languages that distinguish between lists (array(1, 2, 3)) and dictionaries or maps (array('a' => 1, 'b' => 2)).
With PHP 5.4 and above:
$array = [
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'geometry' => [
'coordinates' => [-94.34885, 39.35757],
'type' => 'Point'
], // geometry
'properties' => [
// latitude, longitude, id etc.
] // properties
], // end of first feature
[] // another feature, and so on
] // end of features
];
For the PHP script below:
<?php
header('Content-type=> application/json');
echo json_encode($array);
This is the JSON output;
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"coordinates": [
-94.34885,
39.35757
],
"type": "Point"
},
"properties": []
},
[]
]
}