I want to return multiple array using json in codeigniter like this :
{
"countData"
[
{"flag":1,"count":3}
{"flag":0,"count":0}
{"flag":1,"count":2}
]
}
I already tried :
$faqdata=array(
'count' => $faqdata['countdata']['resultdata']['count'],
)
$listfaqcount['count_Data'][]=$faqdata;
$listfaqcount['flag'] =1;
$j_r=json_encode($listfaqcount);
echo $j_r;
Like this way for two more array .flag would be zero in else condition which I didn't mention here.
How can I do this? Please help.
Thanks in advance
You can do something like this
$listfaqcount['countData'][0] = array(
'flag' => 'flagValue',
'count' => 'countValue'
);
While you looping you change the index with your key like that
$listfaqcount['countData'][1] = array(
'flag' => 'flagValue',
'count' => 'countValue'
);
and so on and while you encoding you can do like this
echo json_encode($listfaqcount);
You need something like array_push
$array['countdata'] = [];
create our sample array sets
$somearray1 = ['flag'=>9,"count"=>5];
$somearray2 = ['flag'=>6,"count"=>6];
$somearray3 = ['flag'=>5,"count"=>7];
$somearray4 = ['flag'=>4,"count"=>8];
Basically what happens here is everytime you loop you push the array inside $array['countdata']
array_push($array['countdata'], $somearray1); //loop 1 format and push
array_push($array['countdata'], $somearray2); //loop 2 format and push
array_push($array['countdata'], $somearray3); //loop 3 format and push
array_push($array['countdata'], $somearray4); //loop 4 format and push
Print the result beautifully or prettily
print_r(json_encode($array,JSON_PRETTY_PRINT));
result would be
{
"countdata": [
{
"flag": 9,
"count": 5
},
{
"flag": 6,
"count": 6
},
{
"flag": 5,
"count": 7
},
{
"flag": 4,
"count": 8
}
]
}
this is just an example you could push your own formatted array.
Related
var_export($response) is an array like below:
array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
The below code gives a result like this: "data": 3. I wanted add a new item called points with the $response array, into all elements. But here, it overwrites the existing array. How can I achieve this?
$dat=array_push($response,array('points'=>"3"));
return response()->json(['data' => $dat], 200);
Expected output:
[
{
"courseId": 14,
"tutorName": "admin",
"points": 3
},
{
"courseId": 15,
"tutorName": "merl",
"points": 3
}
]
As mentioned, array_push() returns the new number of elements in the array. That's why you get 3.
You can add your value in all elements of the current response, like this:
foreach ($response as $key => $value) {
$response[$key]['points'] = 3;
}
Then, just return the response :
return response()->json($response, 200);
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 am trying to extract JSON document subtree that's indexed by numerical key.
My JSON string:
{
"pk": 20,
"tree": {
"100": {
"values": [
1, 2, 3
]
},
"abc" => 999
}
}
My code:
$session = mysql_xdevapi\getSession("mysqlx://root:letmein#localhost");
$schema = $session->getSchema('test');
$coll = $schema->getCollection('myColl');
$expr = mysql_xdevapi\Expression('$.tree.*');
$result = $coll->find('$.pk=20')->fields(['$.tree[100]'])->execute();
Using '$.tree[100]' results in
[
'tree' => null
]
Using '$.tree.*' results in
[
'tree' => [
0 => [
1, 2, 3
],
1 => 999
]
]
Using '$.tree.abc' results in
[
'tree' => [
'abc' => 999
]
]
So, '$.tree.abc' works, but '$.tree[100]' doesnt.
Question. How can I access values key using '$.tree[100]' expression?
Thanks!
Thnx for report, following case:
$expr = mysql_xdevapi\Expression('$.tree."100"');
$result = $coll->find('$.pk=25')->fields($expr)->execute();
will be supported in mysql_xdevapi v8.0.18 which is planned for Oct 14.
Performing a query that simulates a 'like/mysql' searching for teams on the name of the team
Team document structure
{
"_id": 9,
"name": "azerty",
"tag": "dsfds",
"desc": "ggdfgsdfgdfgdf",
"captain": 8,
"coach": 8,
"members": [{
"date_joined": "2016-03-31 15:22:09",
"user_id": 8
}, {
"date_joined": "2016-03-31 19:22:35",
"user_id": 9
}],
"current_invites": [{
"invite_id": 21,
"username": "Nikki",
"user_id": "9",
"status": 1,
"date_invited": "2016-03-31 18:32:40"
}, {
"invite_id": 22,
"username": "Nikki",
"user_id": "9",
"status": 2,
"date_invited": "2016-03-31 18:33:16"
}]
}
PHP Code =
$q = '/.*'.$q.'*./';
$result = $this->coll->aggregate(
array('$match' => array('name' => $q)),
array('$project' => array('name' => 1,'members' => array('$size' => '$members'))));
Feels like I'm going mad not knowing how to fix this.
Have used regex before after migrating to mongo but not with the combination of agg-match.
in my case i am finding the aggregated result in which you can not set the where clause so use the aggregated functions like $sort $unwind $orderby and so on i am using the all of the above mention and have the problem with the like stuff to match the string like %str% here my code in which i implement the like using $match with MongoRegex
public function getRecords($table,$where = array(),$like_key = false,$like_value = false,$offset = 1,$limit = 10,$order_column = false,$order_type = false, $isAggregate=false,$pipeline=array()){
$temp = $this->getMongoDb()->where($where);
if($like_key && $like_value){
$temp = $temp->like($like_key,$like_value);
// this like filter is for aggregated result work both on normal get record or by aggregated result
$pipeline[]=array(
'$match' => array( $like_key => new MongoRegex( "/$like_value/i" ) )
);
}
if($order_column && $order_type){
$order_by = array();
$order_by[$order_column] = $order_type;
$temp = $temp->order_by($order_by);
$pipeline[]=array(
'$sort'=>array($order_column => ($order_type =="desc")? -1 : 1)
);
}
I got the solution when I read the following aggregation framework go the aggregation framework
I hope you will get your solution to resolve your issue.
I have the following code in PHP to connect to my MongoDB instance:
$connection_string = "mongodb://XXXXXXX:XXXXXX#XXXXX:XXX/myDB";
$mongo_or = new Mongo($connection_string);
$db_or = $mongo_or->selectDB("myDB");
# Pick a collection
$collection_or = $db_or->myCollection;
$findArray = array('$and' => array('user.uid' => 1, 'friend_id' => 2));
$findArray2 = array('$and' => array('user.uid' => 2, 'friend_id' => 1));
$collection_or->remove($findArray);
$collection_or->remove($findArray2);
This never removes any results - even know the content is still there it never get's removed.
if you want the good structure for a $and query just json_decode this :
{
"$and" : [{
"$or" : [{
"civility" : 2
}, {
"civility" : 3
}]
}]
}