I am struggling for quite a while on how to access nested object.
$dt = Carbon::parse($year.'-'.$month.'-1');
$godziny = array();
$gs = $lekarz->od;
$gz = $lekarz->do;
$ile = $gz-$gs;
for($j=0; $j<4*$ile; $j++){
if($j%4==0){
$wm = "00";
}
else{
$wm = ($j%4)*15;
}
if($gs+floor(($j/4)) < 10){
$dz="0".$dz = $gs+floor(($j/4));
} else{
$dz = $gs+floor(($j/4));
}
$godziny[$j]['godzina'] = $dz;
$godziny[$j]['minuty'] = $wm;
if(!empty(Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->get())){
$godziny[$j]['odbyta'] = Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->get();
dd(get_object_vars($godziny[$j]['odbyta']));
// $godziny[$j]['pacjent'] = Pacjent::where('id', '=', $godziny[$j]['odbyta']->{0}->pacjent_id);
} else {
$godziny[$j]['odbyta'] = '';
}
}
Everything works except for the last part. It seems like whatever way i try to access this data ( by using $godziny[$j]['odbyta']['pacjent_id'] or by $godziny[$j]['odbyta']->pacjent_id) it just won't work. I really don't know what to do.
That's my [$j]['odbyta] data:
{
"id": 1,
"pacjent_id": "13",
"lekarz_id": "1",
"data": "2017-04-05 10:15:00",
"odbyta": "0",
"created_at": "2017-04-05 16:14:42",
"updated_at": "2017-04-05 16:14:42"
}
That is code that generates data with a pattern:
$j's max number is 36
$godziny[0]['godzina'] = $dz //That's for setting hour to array
$godziny[0]['godzina'] = $wm; //That's for assigning minutes
$godziny[0]['odbyta'] <- that's of value of object that i listed above
How can i possibly access data from this object?
so $godziny[0]['odbyta'] can give me an value of object it contains?
Can't you just use Model->where...first()? and than access it as object:
$godziny[$j]['odbyta'] = Kolejka::where('data', 'LIKE', $year.'-'.$month.'-'.$day.' '.$dz.':'.$wm.'%')->first();
$godziny[$j]['pacjent'] = Pacjent::where('id', '=', $godziny[$j]['odbyta']->pacjent_id);
Related
#UPDATED
I have this table :product_img_detail Table
i want to put the result to make this array of json:
{
"selectedColor": "black",
"black": {
"thumb": {
"image1": "../img/e-commerce/product/dark-small-1.jpg",
"image2": "../img/e-commerce/product/dark-small-2.jpg",
"image3": "../img/e-commerce/product/dark-small-3.jpg"
},
"large": {
"image1": "../img/e-commerce/product/dark-large-1.jpg",
"image2": "../img/e-commerce/product/dark-large-2.jpg",
"image3": "../img/e-commerce/product/dark-large-3.jpg"
}
},
"selectedSlide": 0
}
and this is what i've tried so far with help of #IT goldman:
$sImg = "SELECT prod_thumb160x90, prod_img1280x720 FROM product_img_detail WHERE prod_id=".$data2['id'];
$qPrd = mysql_query($sImg);
$rPrd = mysql_fetch_array($qPrd);
$imgPath = "img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
foreach ($rPrd as $row) {
$count++;
$arrSm["image$count"] = $imgPath.$rPrd['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath.$rPrd['prod_img1280x720'];
}
$arrImg = array("thumb"=>$arrSm, "large"=>$arrLg);
$res = array("selectedColor"=>"black", "black"=>$arrImg, "selectedSlide"=>0);
echo $json = json_encode($res);
the output of above code is:
{
"selectedColor": "black",
"black": {
"thumb": {
"image1": "img\/e-commerce\/product\/dark-small-1.jpg",
"image2": "img\/e-commerce\/product\/dark-small-1.jpg",
"image3": "img\/e-commerce\/product\/dark-small-1.jpg",
"image4": "img\/e-commerce\/product\/dark-small-1.jpg"
},
"large": {
"image1": "img\/e-commerce\/product\/dark-large-1.jpg",
"image2": "img\/e-commerce\/product\/dark-large-1.jpg",
"image3": "img\/e-commerce\/product\/dark-large-1.jpg",
"image4": "img\/e-commerce\/product\/dark-large-1.jpg"
}
},
"selectedSlide": 0
}
I'm curious, if i change the query to select * from the table, it looping until "image10", and if i change the query to select only 1 column from the table, it stop looping at "image2"!
Anyone can help me?
Please help i need to restructure with right & efficient code (and unescape the forwardslash), i've already stuck for 3 days...
After combining with #IT goldman code, i've found the answer:
$sImg = "SELECT * FROM product_img_detail WHERE prod_id=".$data2['id'];
$qPrd = mysql_query($sImg);
$imgPath = "img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
//foreach ($rPrd as $row) {
while($rPrd=mysql_fetch_array($qPrd)){
$count++;
$arrSm["image$count"] = $imgPath.$rPrd['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath.$rPrd['prod_img1280x720'];
}
$arrImg = array("thumb"=>$arrSm, "large"=>$arrLg);
$res = array("selectedColor"=>"black", "black"=>$arrImg, "selectedSlide"=>0);
echo $json = json_encode($res);
You need to loop the records (rows) and aggregate to the arrays with the proper keys (according to $count)
You need to loop the records (rows) and aggregate to the arrays with the proper keys (according to $count)
EDIT: I fixed usage of the now deprecated mysql_fetch_array
<?php
$sql = "SELECT * FROM product_img_detail WHERE prod_id = " . $data2['id'];
$qPrd = mysql_query($sql);
$imgPath = "../img/e-commerce/product/";
$count = 0;
$arrSm = [];
$arrLg = [];
while ($row = mysql_fetch_array($qPrd, MYSQL_ASSOC)) {
$count++;
$arrSm["image$count"] = $imgPath . $row['prod_thumb160x90'];
$arrLg["image$count"] = $imgPath . $row['prod_img1280x720'];
}
mysql_free_result($qPrd);
$arrImg = array("thumb" => $arrSm, "large" => $arrLg);
$res = array("selectedColor" => "black", "black" => $arrImg, "selectedSlide" => 0);
echo $json = json_encode($res);
I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.
I have a task on my Laravel project that runs every day and check for expiration on some coupons. If they expire that day, I add them as array to the user table to display them on the admin panel. Problem is, client wants them to be shown joined if they share date and price properties and I'm having some trouble finding the appropriate way to do this. Let me explain:
$coupons = Coupon::where([['date_end', date('Y-m-d')], ['status', '!=', 0]])->get();
foreach ($coupons as $key => $coupon)
{
$user = User::where('id', $coupon->user_id)->first();
$coupon->status = Coupon::EXPIRED;
$coupon->save();
if ($user->expired_coupons == NULL)
{
$coupons_expired = [];
}
else
{
$coupons_expired = json_decode($user->expired_coupons);
}
$last_coupon_expired['date'] = $coupon->date_end;
$last_coupon_expired['quantity'] = 1;
$last_coupon_expired['price'] = $coupon->voucher->available->price_per_meal;
$coupons_expired[] = $last_coupon_expired;
$user->expired_coupons = $coupons_expired;
$user->save();
}
And I'll get something like this in the db:
[{
"date": "2020-05-24",
"quantity": 1,
"price": 5
}, {
"date": "2020-05-24",
"quantity": 1,
"price": 5
}, {
"date": "2020-05-24",
"quantity": 1,
"price": 10
}, {
"date": "2020-05-23",
"quantity": 1,
"price": 5
}]
Which looks like this in my admin panel:
And in this case, the way I'd want it to show would be:
- 2020-05-24 || 2 || 5
- 2020-05-24 || 1 || 10
- 2020-05-23 || 1 || 5
If I didn't need the quantity I could just get rid of the arrays that are exactly equal, but everything I tried to get the thing working as I want to has failed. Any pointers? Thanks.
If it is possible to share the data what you have got $coupons variable. But i tried to solve the problem by grouping the date and price. May be there need to more improvement.
$coupons = Coupon::where([['date_end', date('Y-m-d')], ['status', '!=', 0]])->get();
$coupons_expired = [];
foreach ($coupons as $key => $coupon)
{
$user = User::where('id', $coupon->user_id)->first();
$coupon->status = Coupon::EXPIRED;
$coupon->save();
if ($user->expired_coupons == NULL)
{
$coupons_expired = [];
}
else
{
$coupons_expired = json_decode($user->expired_coupons);
}
if (isset($coupons_expired[$coupon->date_end][$coupon->voucher->available->price_per_meal])) {
$coupons_expired[$coupon->date_end][$coupon->voucher->available->price_per_meal]['quantity']++;
} else {
$coupons_expired[$coupon->date_end][] = [
$coupon->voucher->available->price_per_meal => [
'data' => $coupon->date_end,
'quantity' => 1,
'price' => $coupon->voucher->available->price_per_meal
]
];
}
$user->expired_coupons = $coupons_expired;
$user->save();
}
$mappedData = [];
foreach ($coupons_expired as $data => $dateGroups) {
foreach ($dateGroups as $qty => $coupon) {
$mappedData[] = $coupon;
}
}
I came up with this solution that, for now, meets my needs. Since the date will always be the same for the coupons that expire (being a daily task) I just create an array with all the prices and the amount of times they appear, and then iterate it to make the final array of coupons expired joined by date and price.
foreach ($coupons as $key => $coupon)
{
$coupon->status = Coupon::EXPIRED;
$coupon->save();
$expired_coupon_price['price'] = (string)$coupon->voucher->available->price_per_meal;
$expired_coupons_prices[] = $expired_coupon_price;
}
$array_prices_unique = array_count_values(array_column($expired_coupons_prices, 'price'));
foreach ($array_prices_unique as $key => $price)
{
$last_coupon_expired['date'] = date('Y-m-d');
$last_coupon_expired['quantity'] = $price;
$last_coupon_expired['price'] = (float) key($array_prices_unique);
$coupons_expired_today[] = $last_coupon_expired;
next($array_prices_unique);
}
if ($user->expired_coupons == NULL)
{
$coupons_expired_from_user = [];
}
else
{
$coupons_expired_from_user = json_decode($user->expired_coupons);
}
$user->expired_coupons = array_merge($coupons_expired_from_user,$coupons_expired_today);
$user->save();
}
I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}
This is almost exactly what I want, but that question hasn't been answered and it's been a year. I've managed to get close, I think, but numbers are being printed as keys. In my example it shows up on line 47, but it is repeated for every "course_name" in the actual file.
[
{
"school_name": "Projects",
"terms": [
{
"term_name":"category_name#1",
"departments": [
{
"department_name":"sub_category_name1",
"department_code":"category code text here",
"courses":[
{
"course_name": "project1",
"course_code":"project 1 code text goes here",
"sections":[
{
"section_code":"mike",
"unique_id":"xxx#mail.com"
},
{
"section_code":"dan",
"unique_id":"xxx#gmail.com"
}
]
},
{
"course_name": "project2",
"course_code":"project 2 code text goes here",
"sections":[
{
"section_code":"steve",
"unique_id":"xxx#mail.com"
},
{
"section_code":"chris",
"unique_id":"xxx#gmail.com"
}
]
}
]
},
{
"department_name": "sub_category_name2",
"department_code":"sub category description text goes here..",
"courses": {
-->>> "69": {
"course_name": "project3",
"course_code":"project3 code text goes here ",
"sections":[
{
"section_code":"Alex",
"unique_id":"xxx#gmail.com"
}
]
}
}
}
]
}
]
}
]
Here is the query I am using and an example of data being returned.
SELECT school_name, term_name, department_name, department_code, course_code, course_name, section_code, magento_course_id
FROM schools INNER JOIN term_names ON schools.id=term_names.school_id INNER JOIN departments ON schools.id=departments.school_id INNER JOIN
adoptions ON departments.id=adoptions.department_id
"UCA-2" "SPRING 2013" "ACCOUNTING" "ACCT" "3315" "COST ACCOUNTING" "10258" 10311
What I have is being generated with this code.
$row_array = array();
$terms = array();
$departments = array();
$courses = array();
$h = 0;
$i = 0;
$j = 0;
while ($row = mysqli_fetch_assoc($fetch)) {
$row_array[$row['school_name']]['school_name'] = $row['school_name'];
$akey = array_search($row['term_name'], $terms);
if ($akey === FALSE) {
$m = $h++;
$terms[] = $row['term_name'];
$row_array[$row['school_name']]['terms'][$m]['term_name'] = $row['term_name'];
} else {
$m = $akey;
}
$key = array_search($row['department_code'], $departments);
if ($key === FALSE) {
$k = $i++;
$departments[] = $row['department_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_name'] = $row['department_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['department_code'] = $row['department_code'];
} else {
$k = $key;
}
$skey = array_search($row['course_code'], $courses);
if ($skey === FALSE) {
$l = $j++;
$courses[] = $row['course_code'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_name'] = $row['course_name'];
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['course_code'] = $row['course_code'];
} else {
$l = $skey;
}
$row_array[$row['school_name']]['terms'][$m]['departments'][$k]['courses'][$l]['sections'][] = array('section_code' => $row['section_code'], 'unique_id' => $row['magento_course_id']);
}
How do I generate this JSON without those numbers showing up?
I think you have some key & encoding problems. Too much key usage, excessive loops in your code. Maybe you should tidy your sql query.
Since you are setting keys for courses, JSON shows it.
Try removing the key after "['courses']" in your last line such as;
Change ['courses'][$l] to ['courses'][]
At the end, encode the array for JSON.
$result = json_encode($result);