In my controller, this statement generates an array:
// sort the region collection by continent for faster access in front end
$finalRegions = $regions->sortBy('continent_id');
{
"0":{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
"1":{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
....
}
}
How do I remove the index from the resulting object, so it looks like this:
[
{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
....
}
]
This is stored in a field cast as json in the table class.
$res = [];
foreach ($finalRegions as $key => $value) {
$res[] = $value;
}
// $res contains desired result
Edit: Simple one liner (thanks to Jannie)
$res = array_values($finalRegions)
Since you have "Laravel" in your question title and it looks like you already have your regions in a Laravel Collection, there is an easier way. Just pipe your results through ->values() after the ->sortBy() clause like this:
$finalRegions = $regions->sortBy('continent_id')->values();
I still don't get why you need to remove those indexes, but you can do by this way.
<?php
$jsonArr = '{
"0":{
"id":1,
"name":"Alaska",
"image_x":227,
"image_y":117
},
"1":{
"id":5,
"name":"Australian Antartic Territory",
"image_x":1187,
"image_y":1037
}
}';
$decodeArr = json_decode($jsonArr, true);
print_r(json_encode($decodeArr));
This is just my idea, and you can edit part of your code where the query returns your JSON string.
Related
i want to add multiple Array item into One Array Object in PHP
i have array like below :
[
{
"name": "AAA"
},
{
"family": "BBB"
},
{
"job": "CCC"
}
]
And i need to Convert like below:
{
"name": "AAA",
"family": "BBB",
"job": "CCC"
}
Array Data maybe changed , but , i write this code for explain my problem :
$RetArray=array();
$Array_Test=array(array('name'=>'AAA'),array('family'=>'BBB'),array('job'=>'CCC'));
foreach ($Array_Test as $json_item){
foreach ($json_item as $key=>$value){
array_push($RetArray,array($key => $value));
}
}
echo json_encode($RetArray);
But this code returns the same as the first array!
I want to return every item into one array.
Try this:
$RetArray=[];
$SrcArray=[
["name"=>"AAA"],
["family"=>"BBB"],
["job"=>"CCC"],
];
foreach($SrcArray as $item){
$RetArray=array_merge($RetArray,$item);
}
echo json_encode($RetArray);
Here is what it got: https://3v4l.org/kZJ2T
you can use array_merge() or array_push()
I have a use defined json string inside a database.
The JSON string has lots of levels. I know my user will define a kay called "basevalue" and place it somewhere in the json.
The problem is, I don't know ahead of time where in the JSON it will be placed, and every use is likely to place is in different places in the array, perhaps at different levels.
This is an example of the JSON data being saved by the user:
{
"name": "",
"type": "layout",
"children": [
{
"name": "",
"type": "section",
"children": [
{
"name": "",
"type": "row",
"children": [
{
"name": "",
"type": "column",
"props": {
},
"children": []
},
{
"type": "column",
"children": [
{
"type": "itemdata",
"props": {
**"basevalue": "100",**
},
"children": []
}
]
}
]
}
]
}
I'm converting this data to an array using json_decode:
$json = json_decode($json, true);
No I need to search through the array, and find the key of 'basevalue' and then get whatever value the user has input, in the case above that would be '100'.
So to the issue is, I have no idea what 'node' the 'basevalue' key will be. It could be 40 deep, it could be in the first 'children' node.
This is up to the user.
So how do I take any version of the JSON string about and return the '100'?
Many thanks.
You can recursively iterate over the data and get the value of the key basevalue. To make this search faster, we can adopt an early exit approach similar to breadth first search. By this, we call add all values who are arrays in a queue and continue our search for the key basevalue and later on deal with pending queue. This would be faster than basic recursion because a lot of times it's possible that key was on the same level but we searched all the way down on all other trees which proved out to be trivial.
Snippet:
function getBaseValue($arr,$search_key){
$pending_calls = [];
foreach($arr as $key => $value){
if(is_array($value)){
$pending_calls[] = $value; // queue them for later judgement
}else if($search_key === $key){
return $value;
}
}
foreach($pending_calls as $call){
$returned_val = getBaseValue($call,$search_key);
if($returned_val !== false) return $returned_val;
}
return false;
}
echo getBaseValue($arr,'basevalue');
Demo: https://3v4l.org/gdLK1
I have arrays in my JSON like this:
[
{
"id":"bobbys_burgers",
"is_enabled":true,
"name":"Bobbys Burgers",
"supported_transactions":[
"222",
"111",
"333"
],
"enrollment_required":[
],
"restricted_transactions":[
"123"
]
},
{
"id":"randys_sandwich",
"is_enabled":true,
"name":"Randys Sandwich",
"supported_transactions":[
"321"
],
"enrollment_required":[
],
"restricted_transactions":[
]
},
]
I want to get all the keys of the whole array where id = randys_sandwich. for example, i want to search for id == randys_sandwich and return the is_enabled, name, supported_transactions, etc AND their values from that array. how can i do that in php?
You need to json_decode your array then loop through the objects in your array find the one with the id you're looking for.
$array = json_decode($json, true);
foreach ($item in $array) {
if ($item['id'] == 'randys_sandwich') {
var_dump($item);
break; // Once you've found the item no need to continue the loop
}
}
How can I get rid of the table name from the keys in the results.
$query = Doctrine_Core::getTable('Apps')
->createQuery('a')
->select("DATE_FORMAT(`created_at`,'%Y/%m') as Month,count(*) as Applications")
->groupBy(" year(`created_at`) , month(`created_at`)");
$query->setHydrationMode(Doctrine::HYDRATE_NONE);
Gives me something like
{
"a_Month": "2012/09",
"a_Applications": "3447"
},
{
"a_Month": "2012/10",
"a_Applications": "565"
},
{
"a_Month": "2012/11",
"a_Applications": "689"
}...
I need to get something like
{
"Month": "2012/09",
"Applications": "3447"
},
{
"Month": "2012/10",
"Applications": "565"
},
{
"Month": "2012/11",
"Applications": "689"
}...
Without the table name prepended, is there any way to do this ?
Internally Doctrine uses its own column names to build queries. The column names assigned by you are applied to the results during hydration. Because you used HYDRATE_NONE you get the Doctrine's names as no hydration is being made on the result set.
Use the HYDRATE_ARRAY mode and you will get an array with keys you assigned yourself.
I don't know Doctrine very well so there might be something native but you could try this ($arr is your results array):
array_map(function ($k, $v) use (&$arr){
$ke = str_replace("a_", "", $k);
$arr[$ke] = $v;
unset($arr[$k]);
}, array_keys($arr), $arr);
Ok, so I have a collection in my MongoDB
here is a sample my key here is
company
{
"_id": ObjectId("4fdfe7b536314b4147000000"),
"company": "hoyts",
"barcode": "236602253",
"name": "Gold Class",
"logoURL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
"store_name": "movies"
}
Now the issue here is I have 4 rows/collects with hoyts, I need away to group them.
my current code
public function getstore($storename)
{
// select a collection (analogous to a relational database's table)
$collection = $this->db->products;
// find everything in the collection
$cursor = $collection->find(array("store_name"=>$storename));
$test = array();
// iterate through the results
while( $cursor->hasNext() ) {
$test[] = ($cursor->getNext());
}
//Print Results
print json_encode($test);
}
I tried using
group($key)->find
however that did not work.
Could someone give me a hand thanks
look at this example: http://php.net/manual/en/mongocollection.group.php