I'm a bit new to PHP and programming in general so please bear with me if I don't explain with the correct phrasing.
I am parsing an array into specific columns in order to later parse that data into a preexisting excel spreadsheet. Each array has specific keys that equate to specific columns.
The part I need help with is the following:
This is part of the array (it repeats this but with different data, an array for each):
{
{
"Batches": "24",
"Timestamp": " ",
"Manager": " ",
"Region": " ",
"Name": " ",
"Cell": " ",
"Email": " ",
"Personalized or Blank": " ",
"FNO's": " ",
"Order Total": " ",
"R289 FF Air": "0",
"R289 T3": "0",
"R399": "0",
"R429": "0",
"R489": "0",
"R599": "0",
"Openserve R549": "0",
"Openserve R299": "0",
"Vumatel": "0",
"Octotel": "0",
"Octotel T3": "0",
"Balwin": "0",
"Evotel": "1000",
"Netstream": "0",
"Metrofibre": "0",
"Vodacom": "0",
"TT Connect": "0",
"WAN": "0",
"Link Africa": "0",
"Ambassador": "0",
"Link Layer": "0",
"Open Fibre": "0",
"Zoom Fibre": "0"
},
This is the loop:
$i = 0;
foreach($Data2022_23 as $item) {
$A[$i] = $item['Order Total'];
$B[$i] = $item['Timestamp'];
$C[$i] = $item['Manager'];
$D[$i] = $item['Region'];
$E[$i] = $item['Name'];
$F[$i] = $item['Cell'];
$G[$i] = $item['Email'];
$H[$i] = $item['Personalized or Blank'];
foreach($Data2022_23 as $key => $value) {
if($key != "Batches" && $key != "Timestamp" && $key != "Manager" && $key != "Region"
&& $key != "Name" && $key != "Cell" && $key != "Email" && $key != "Personalized or Blank"
&& $key != "FNO's" && $key != "Order Total" && $value != "0"){
$J = array_keys($Data2022_23, $key);
}
}
$i++;
}
From $A to $H works, those are the specific columns, I need help with assigning $J the value of the key which is not 0, ie. "Evotel" as per the array above. I have tried tinkering the nested foreach loop in the code above but I am struggling to get the correct data output.
Any assistance will help.
I've tried different iteration of the nested for each loop, such as:
Assigning $J the $key, which return the index not the string.
$J = $key;
Trying a whole lot of tinkering on the foreach loop but none of it really worked.
I'm trying to get $J to have the value of the key, not the index which I keep getting.
Something like:
echo $J;
With result:
Array([0] => "Evotel")
or something like that.
Related
i want to delete some index with comparing but it is not easy
first one our php version is 5
for example my result is like this
it is echo by json_encode and it was array
and the data is dynamic
[
{
"idx": "1",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
},
{
"idx": "2",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-10 08:30:00",
},
{
"idx": "3",
"mom_member_idx": "2",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
}
]
and i want to result like this comparing and unset with the latest one
[
{
"idx": "1",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
},
{
"idx": "3",
"mom_member_idx": "2",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
}
]
i tried like this but it is not work
while ($r = mysqli_fetch_assoc($chat_list)) {
$dbdata[] = $r;
}
for($r=0;$r<sizeof($dbdata);$r++){
if ($dbdata[$r]['mom_member_idx']+$dbdata[$r]['teacher_member_idx']==$dbdata[$r+1]['mom_member_idx']+$dbdata[$r+1]['teacher_member_idx'])
{
if($dbdata[$r]['care_start_datetime']<$dbdata[$r+1]['care_start_datetime']){
unset($dbdata[$r]);
}else {
unset($dbdata[$r+1]);
}
}
}
First, convert your JSON array into a PHP array. then you can remove the array elements using the array index
$someArray = json_decode($someJSON, true);
You can sort the data by descending order by care_start_datetime using usort() and unset the first index form that sorted data.
Code example:
$data = json_decode('[
{"idx": "1","mom_member_idx": "1","teacher_member_idx": "2","care_start_datetime": "2019-09-09 08:30:00"},
{"idx": "2","mom_member_idx": "1","teacher_member_idx": "2","care_start_datetime": "2019-09-10 08:30:00"},
{"idx": "3","mom_member_idx": "2","teacher_member_idx": "2","care_start_datetime": "2019-09-09 08:30:00"}
]', true);
usort($data, function($a, $b) {
return strtotime($a['care_start_datetime']) > strtotime($b['care_start_datetime']) ? -1 : 1;
});
unset($data[0]);
print_r($data);
Working demo.
Your variant with summing to columns is not totally correct, because sum of some integers give you wrong result and you can accidentally remove the wrong one. Like 2 + 3 == 1 + 4 not correct.
Maybe that code helps you:
$groupedData = array();
while ($r = mysqli_fetch_assoc($chat_list)) {
// We create unique key for group same rows
// (with the same 'mom_member_idx' and 'teacher_member_idx')
$uniqueKey = implode('_', [$r['mom_member_idx'], $r['teacher_member_idx']]);
if (!array_key_exists($uniqueKey, $groupedData)) {
$groupedData[$uniqueKey] = array();
}
// Add row to grouped array by our unique key
$groupedData[$uniqueKey][] = $row;
}
$result = array();
foreach ($groupedData as $rows) {
// If in grouped array with that unique key only one row - just add it
if (count($rows) <= 1) {
$result[] = $rows[0];
continue;
}
// Go for all same rows and check date
$neededRow = null;
foreach ($rows as $row) {
// Here I don't understand what kind of date do you want - minimum or maximum
// You just can reverse the sign
if (
is_null($neededRow) ||
strtotime($row['care_start_datetime']) > strtotime($neededRow['care_start_datetime'])
) {
$neededRow = $row
}
}
if ($neededRow) {
$result[] = $neededRow;
}
}
For delete specific index first you need to convert JSON array into PHP array using json_decode() function, once you convert it into PHP array you can remove specific index using key,
foreach ($data as $key => $element) {
$value = $element['...'];
if (...) {
unset($data[$key]);
// or
$data[$key]['...'] = '...';
}
}
Hope this helps you.
"data": [
{
"pid": "81",
"fname": "Parth",
"lname": "Tandel",
"pfname": "Parth",
"plname": "Tandel",
"userprofilephoto": "/Images/ProfilePictures/18/DSC_0164.JPG",
"parentprofilephoto": "/Images/ProfilePictures/18/DSC_0164.JPG",
"type": "ALBUM",
"likescount": "1",
"commentscount": "1",
"sharecount": "0",
"sharepid": null,
"uaid": "18",
"ownerid": "18",
"parentid": null,
"title": "newalbum2",
"description": "",
"sharedescription": null,
"imagepath": null,
"previewurl": null,
"previewtitle": null,
"previewshortdescription": null,
"previewimageurl": null,
"createdon": "2017-05-29 15:44:04",
"posttype": "5",
"comments": [
{
"pcid": "21",
"uaid": "31",
"comment": "this is dope",
"fname": "maulik",
"lname": "kanani",
"profPicturepath": "https://www.gravatar.com/avatar/003dbb32079ee5ff19ed75476f562bd1",
"createdon": "2017-06-15 23:50:36"
}
],
"albumimages": [
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-36.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-361.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-363.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-364.png"
},
{
"imagepath": "/Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-365.png"
}
]
}
My PHP code
<?php
for ($i=0; $i < sizeof($value->albumimages); $i++)
{
$x = count($value->albumimages);
switch($x)
{
break;
default:
if($i == 0 || $i == 1)
{
echo '<div class="col-sm-6 pads5 marb10"> <img class="full" src="'.getapiPath().$imgs->imagepath.'"> </div>';
}
break;
}
}
?>
I want albumimages->imagepath
I think what you are looking for is json_decode($data, true);
This makes the json data an array that you can use like var_dump($data["albumimages"])
Working example: https://3v4l.org/Q9lkW
And to loop through the links you can do foreach, https://3v4l.org/9rRSF
Use this code
$a = json_decode('YOUR JSON STRING',true);
foreach($a['data'][0] as $key => $value){
if($key == 'albumimages'){
for($i = 0; $i < count($value); $i++){
foreach($value[$i] as $k => $v){
echo "Key: ".$k." Value: ".$v."<br/>";
}
}
}
}
Output will be like this
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-36.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-361.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-363.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-364.png
Key: imagepath Value: /Images/18/Albums/newalbum2/Screenshot_from_2017-06-12_15-11-365.png
for ($i=0; $i < sizeof($value->albumimages); $i++) {
$x = count($value->albumimages);
switch($x) {
default:
if($i == 0 || $i == 1)
{
echo '<div class="col-sm-6 pads5 marb10"> <img class="full" src="'.getapiPath().$value->albumimages[$i]->imagepath.'"> </div>';
}
break;
}
}
The data is in json format so convert the data into php object by using 'json_encode()' function. This function converts the json data into php object the access the property by using php object operator.
$data = json_encode('your_json_string');
//and access like this
$data[0]->albumimages
You can use the foreach loop to access the 'imagepath' like this
//get the albumsimages
$albumimages = $data[0]->albumimages;
//then use foreach to access the imagepath like this
foreach($albumimages as $image) {
echo $image->imagepath ."\n";
}
Check out working example here
PHP sandbox
I wrote a function to accept a 'product_id' and then it will cycle through all my Json fields to find all the json objects without the id 'product id' and then I need it encode it back and update database.
currently I substituted 'product_id' with '154' since that is a 'id' I am testing to remove.
This Foreach statement I wrote gets me all the ids
$user = $this->session->userdata('user_id');
$autoOrder = $this->db->get_where('auto_order', ['user_id' => $user])->row()->products;
$temp = json_decode($autoOrder);
foreach ($temp as $value) {
$last_value = (array)$value;
foreach ($last_value as $key=> $value) {
foreach($value as $key2=>$value2) {
if ($key2 == 'id' && $value2 != '154') {
echo "Product Id: " . $value2 . "<br>";
$new_ids[] = $value2;
}
}
}
}
How can I now cycle through all the autoOrder and retrieve only the ones with 'new_ids'?
Example How The JSON Looks:
[
{
"order": {
"id": "154",
"qty": "1",
"option": "{\"color\":{\"title\":\"Color\",\"value\":null}}",
"price": "2433.62",
"name": "Race Car",
"shipping": "0",
"tax": "26",
"image": "http://localhost/products/image/34",
"coupon": ""
}
}
]
This code you wrote it's a bit complicated to understand.
Anyway, you should save the new_ids into the DataBase, and then execute the query specifying the condition to retrieve only the object without new_ids on the WHERE.
I want to show percent of department depend on date in c3js chart with timeseries.
I have four department id, and I query the result like this.
$dept_id_arr = array();
$date_arr = array();
$percent_arr = array();
$sql = ........;
$rsl = mysql_query($sql);
while($get = mysql_fetch_assoc($rsl)){
$date_arr[] = $get['date'];
$dept_id_arr[] = $get['department_id'];
$percent_arr[] = $get['total_percent'];
}
When I print this data with var_dump(), I got like this,
string(66) "["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"]"
string(22) "["1","3","1","1","2"]"
string(46) "["0.5700","0.0000","0.5700","0.0000","0.5700"]"
I want to change that value to like this,
[{
"date": "2015-11-17",
"department1": "0.5",
"department2": "0.9",
"department3": "4",
"department4": "3",
}, {
"date": "2015-11-18",
"department1": "0.5",
"department2": "0",
"department3": "0",
"department4": "0",
}, {
"date": "2015-11-19",
"department1": "0.5",
"department2": "0.3",
"department3": "5",
"department4": "2",
}]
because I need to show that data in c3js chart. But I have problem, when I change data to that format because of some date are same in array.
You can do all the things by this code:
<?php
$date = ["2015-11-17","2015-11-17","2015-11-18","2015-11-20","2015-11-23"];
$departmeent = ["1","3","1","1","2"];
$percentage = ["0.5700","0.0000","0.5700","0.0000","0.5700"];
$array = array();
for($i=0; $i<5;$i++)
{
if(array_key_exists($date[$i], $array))
{
$array[$date[$i]]['department'.$departmeent[$i]]= $departmeent[$i];
$array[$date[$i]]['per'.$departmeent[$i]]= $percentage[$i];
}
else
{
$array[$date[$i]] = array('department'.$departmeent[$i] => $departmeent[$i],
'per'.$departmeent[$i] => $percentage[$i]) ;
}
}
echo var_dump($array["2015-11-17"]["department1"]);
echo '<br><br><br><br><br><br>'.json_encode($array);
?>
I have the following JSON file:
[
{
"1421999354744": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:19:14",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:19:14",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
},
{
"1421999527002": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:22:06",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:22:06",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
},
{
"1421999580405": {
"article_id": "213123",
"artfile_status": "",
"process_starttime": "2015\/01\/23 13:23:00",
"process": "Validator",
"process_endtime": "2015\/01\/23 13:23:00",
"process_status": "COMPLETED",
"sub_process_name": "",
"percentage_completed": "100",
"XML_Validity": "false",
"process_type": "AUTO"
}
}
]
I need to get the values of article_id in the above. I've tried to read the multiple dimension but it shows an error.
The code that I have is as follows:
foreach ($response as $key => $value) {
$t = $response[$i];
foreach ($t as $key1 => $value2) {
echo $t[$j]['article_id'];
$j++;
}
$i++;
}
The first array values will be dynamic.
Any help would be appreciated!
You do not need counters at all(in your case $i, $j). You can extract the value from the array by iterating over the array and extracting the data directly from the current value of the iterator:
foreach ($response as $key => $value) {
// Get the first value of the sub-array array,
// which is actually the array you want to extract values from
$value = current($value);
// Print out the article id value
// if your json has been decoded as an array use $value['article_id']
echo $value->article_id;
}