while ($v = $stmt - > fetch(PDO::FETCH_ASSOC)) {
$basicinfo[] = array('sysid' => $v['sysid'], 'thesis' => $v['thesis']);
}
$input = array_map("unserialize", array_unique(array_map("serialize", $basicinfo)));
echo json_encode(array_values($input), JSON_UNESCAPED_UNICODE);
}
this is how i make an array from database i want to make a multidimensional array that i can access from ajax request like data[i].group[j].leader i want to create another array inside the first array which is named thesis. I want to name that array group to represent the number of group that are taking up the subject thesis. Inside this array i want to put the value of the members of that group. I can also add another array inside the array thesis, it will be an array with same level as the array group. i have tried doing it like this
$basicinfo[$group] = array('sysid' => $v['sysid'], 'thesis' => $v['thesis'],"$group=>array('leader' => $v('leader_name'))");
I want the array to look like this
[{
"sysid": "015-08-0004-001-063-2001",
"subject": "thesis",
"group": {
"groupid": "1",
"groupleader": "John",
},
"adviser": {
"advisername": "Prof Smith",
}
}]
i want it like this so i can access each array in the ajax(jquery) like
data[i].group[j].leader
data[i].adviser[j].advisername
Update
i still need to add more table and i think more columns for now this is what i am working with
Related
I'm a newbie to PHP and I want to split a json object that I have stored in a variable into multiple json objects.
My input looks like this :
{
"results":[
{
"id":"001",
"items":{
"item11":"value1",
"item12":"value2",
"item13":"value3"
},
{
"id":"002",
"items":{
"item21":"value1",
"item22":"value2",
"item23":"value3"
},
{
"id":"003",
"items":{
"item31":"value1",
"item32":"value2",
"item33":"value3"
}]
}
I want to first extract each id and store it into a variable and associate to each id the correspondant json that will look like this :
$id1 = "001";
{
"item11":"value1",
"item12":"value2",
"item13":"value3"
}
Try this loop over each record and save it in result.
$json=json_decode($str,true);
array_map(function($value) use (&$results){
$results[$value['id']]=json_encode($value['items']);
return $results;
}
,$json['results']);
print_r($results);
output
Array (
[001] => {"item11":"value1","item12":"value2","item13":"value3"}
[002] => {"item21":"value1","item22":"value2","item23":"value3"}
[003] => {"item31":"value1","item32":"value2","item33":"value3"} )
if you want to display every array item in results, you can use extract($arr['results'])
but if you want to have specific name you should use loops to do it, depend on your pattren
I'm currently building an array off of an object and I've got one element called images that has multiple sub elements called 'urls' structured like so
categories": [
{
"images": [
{
"urls": [
"path/test.jpg",
"path/test2.jpg",
"path/test3.jpg"
],
},
{
"urls": [
"path/test4.jpg",
"path/test5.jpg",
"path/test6.jpg"
],
},
{
"urls": [
"path/test7.jpg",
"path/test8.jpg",
"path/test9.jpg"
],
},
]
The values there don't have keys, it's just the url path but I'd like to add these to my $groupItem array and just have each url be it's own element on the same level as the group number (basically I'm exporting and need each url as it's own column)
The structure I want
0 =>"path/test.jpg",
1 =>"path/test2.jpg",
2 =>"path/test3.jpg"
3 =>"path/test4.jpg",
4 =>"path/test5.jpg",
5 =>"path/test6.jpg"
6 =>"path/test7.jpg",
7 =>"path/test8.jpg",
8 =>"path/test9.jpg"
The loop/array:
foreach($prices->groups as $group){
$groupItem = array();
$groupItem["number"] = $group->number;
foreach($group->images as $images){
$groupItem["urls"] = $images->urls;
}
}
How can I simply just add on any url to the groupItem level of that array?
Outside the outer loop, init the value to an empty array:
$groupItem["urls"] = [];
Then use the empty array reference operator to append new values to the end of an array:
foreach($group->images as $images){
$groupItem["urls"][] = $images->urls; // add this url to the end of the list
}
Alternatively, use array_push():
foreach($group->images as $images){
array_push($groupItem["urls"], $images->urls);
}
I think you can probably also skip the inner loop and just use the array explode operator like this:
array_push($groupItem["urls"], ...$images->urls);
You might also use array_column with (from php 5.6) a variable length argument list:
For example, for the images which contains an array of objects where each object has a property urls and contains an array of image urls:
foreach ($prices->groups as $group) {
$groupItem = array();
$groupItem["number"] = $group->number;
$groupItem= array_merge($groupItem, ...array_column($group->images, "urls"));
}
Demo
I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get
$result['id']
$result['company']
for each row of the returned database suggestiions
This works fine and currently I loop over the results
foreach ($result as $item) {
$suggest[] = $item['company'];
}
echo json_encode($suggest);
I want though to add these so the company is a label and id is a value, something like
"value": "A Company", "data": "20"
This I can then encode and use in my autosuggest.
Thanks in advance!
You have to save an array to main array like this
foreach ($result as $item) {
$suggest[] = [
'value' => $item['company'],
'data' => $item['id'],
]
}
echo json_encode($suggest);
And it should return something like this
[
{
'value': 'Some value',
'data' : item id
}
]
i will recommend you create an array, next create 2 more arrays as values for the value and data keys.
like this.
$arr=array();
$arr['value']=array();
$arr['data']=array();
while($suggest=mysql_fetch_assoc($result)){
array_push($arr['value'],$suggest['id']);
array_push($arr['data'],$suggest['company']);
}
echo "<pre>";
print_r($arr);
note that with this solution, if you delete an entry in either value or data
be ready to delete the corresponding entry in the other array.
others may be able to improve this or even offer a better approach.
I have an array of 3 companies, which need to be inserted into the db but with 2 additional parameters added to them.
$companyList = [{"name": "apple", "founder": "steve"},
{"name": "google", "founder": "larry"},
{"name": "facebook", "founder": "mark"},
];
Need to append these 2 parameters for each company (issue is in this step):
$companyListFinal = [];
foreach ($companyList as $company) {
$companyListFinal[] = array_add($company,['keyAppend1' => 'key 1 appended',
'keyAppend2' => 'key 2 appended'];
}
The final step is to insert the company list with the appended values into the DB:
DB::table('companies')->insert($companyListFinal);
I can't seem to be able to append the 2 new parameters to create the final array to insert:$companyListFinal
What's the correct way to add the parameters to each company so they are all inserted at bulk?
You need to use array_merge instead of array_add
Try using array_push() instead on array_add(). That should do the job.
I have produced an array of fruits stored somewhere. Say it looks like this
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
This array is then passed into a function that will return json-encoded data for an API.
First, I wanted to be able to return a list of all the types of fruits I have
{"fruits":["apples", "oranges", "bananas"]}
I used this to accomplish it
echo json_encode(array("scripts" => array_keys($scripts)));
Now, I would like each type of fruit to be contained in its own hash, as such
{"fruits":
[
{name: "apples"
},
{name: "oranges"
},
{name: "bananas"
]
}
This way I can add additional fields to each fruit object without breaking existing code that may be using previous versions of this API (eg: if I decided to add the fruit counts in there as well).
Seeing how I can just create a new array and assign my list of fruits to a key called "fruits", I tried to do the same for each inner hash:
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
$data = array();
foreach ($myFruits as $key => $value) {
// initialize an associative array for each fruit
$val = array();
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
}
// assign list of fruits to "fruits" key
$outData = array("fruits" => $data);
echo json_encode($outData);
But I get this instead
{"fruits":[[{"name":"apples"}],[{"name":"oranges"}],[{"name":"bananas"}]]}
There are extra square braces around each fruit hash, which I assume is because I'm using an array to store each key-value pair.
How would I get my desired output?
You're close to knowing what you're doing wrong. You're creating an array, and then just using it to add one item (another array) to it.
// initialize an associative array for each fruit
$val = array(); // this guy here is unnecessary!!
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
Instead, just push each individual array onto $data directly like this:
array_push($data, array("name" => $key));
DEMO
You are creating an extra level in your array, simply push a new array onto $data in each iteration:
foreach ($myFruits as $key => $value) {
$data[]=array("name" => $key, "count" => $value);
}
*edited as per your comment