I have multidimensional array($array) like this,
{
"2015-11-17": {
"department1":"0.5700",
"department3":"0.0000"
},
"2015-11-18": {
"department1":"0.5700"
},
"2015-11-20": {
"department1":"0.0000"
},
"2015-11-23": {
"department1":"1.7100",
"department2":"1.7100",
"department3":"2.8500",
}
.
.
.
}
This is a dynamic array and that data are get from database. All data are exists in $array variable. The above data are more than that. I just show a little, because the data are get from database.
I want to show that data on c3js chart like this format,
json:[{
"date": "2015-11-17",
"department1": ""0.5700"",
"department2": "0.0000",
"department3": "0.0000",
"department4": "0.0000",
}],
And I need to show four department data for each date.
In the array, you can see some day have one or two department. I want to add all four department for each day when I change above json format to show in chart.
For example, in 2015-11-17, it has department1 and 3. I want to add next department2 and 4 with '0' in this day.
I want to add another department for each day just like that.
When I try to change $array to above format, I don't get the correct result.
Here is what I try,
<div id='chart'></div>
<script>
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'date',
xFormat: '%Y-%m-%d',
json:[
<?php
for ($i = 0; $i < count($array); $i++) {
$key=key($array);
$val=$array[$key];
if ($val<> ' ') {
foreach ($val as $k=>$v) {
?>
{
'date':<?php echo $key?>,
<?php echo $k?> : <?php echo $v?>,
},
<?php
}
}
next($array);
}
?>],
},
legend: {
position: 'right',
},
line: {
width:0.5
},
axis: {
x: {
type: 'timeseries',
tick:{
format: '%Y-%m-%d',
rotate: 75,
},
label: {
text: 'Date',
position: 'outer-center'
}
}
},
grid: {
y: {
show:true,
}
},
});
</script>
So, now I have problem to show array data in chart. I'm very appreciate for any answer and suggestion.
Here is the sample of dynamic chart image of what I want,
Kindly check the below code. Points to note:
- $deptNames = array of department names as shown in example output.
- $dataArray = is the array which comes from database directly
- instead of echoing output you can save it to any variable and access accordingly.
$deptNames = array('department1','department2','department3','department4');
$resultArray = array();
$index = 0;
foreach($dataArray as $date => $data) {
$resultArray[$index] = array();
if(is_array($data)) {
$dataDeptNames = array_keys($data);
$diff = array_diff($deptNames,$dataDeptNames);
if($diff && count($diff) > 0) {
foreach($diff as $notExistDept) {
$data[$notExistDept] = "0.0000";
}
}
$resultArray[$index] = $data;
$resultArray[$index]['date'] = $date;
ksort($resultArray[$index]);
}
$index++;
}
echo json_encode($resultArray);
It will give you output as:
[
{
"date":"2015-11-17",
"department1":"0.5700",
"department2":"0.0000",
"department3":"0.0000",
"department4":"0.0000"
},
{
"date":"2015-11-18",
"department1":"0.5700",
"department2":"0.0000",
"department3":"0.0000",
"department4":"0.0000"
},
{
"date":"2015-11-20",
"department1":"0.0000",
"department2":"0.0000",
"department3":"0.0000",
"department4":"0.0000"
},
{
"date":"2015-11-23",
"department1":"1.7100",
"department2":"1.7100",
"department3":"2.8500",
"department4":"0.0000"
}
]
Well if you get the array and is stored in a variable, then you can use this pure JS function to convert it to the format you need:
var convertArr = function(x){
var y = [];
for (var k1 in x) {
if (x.hasOwnProperty(k1)) {
var obj = {};
obj['date'] = k1;
var tmp = [];
for (var k2 in x[k1]){
if (x[k1].hasOwnProperty(k2)){
tmp.push(k2[k2.length-1]);
obj[k2] = x[k1][k2];
}
}
var no = ["1","2","3","4"];
var tmpSet = new Set(tmp);
var noSet = new Set(no);
var diff = no.filter(function(z) { return !tmpSet.has(z); })
.concat(tmp.filter(function(z){ return !noSet.has(z); }));
for (var i = 0; i < diff.length; i++){
obj['department'+diff[i]] = '0.0000';
}
y.push(obj);
}
}
return y;
}
From there you can proceed.
Hope it helps.
Related
So I've been experimenting with Chart.js lately and I'm working on a project where I need to loop three Charts dynamically and I need each of them to have their own Custom Legend generated by the generateLegend() function. The problem is that the functionality of the legends isn't correct. Clicking any of the legends seems to affect only the last iteration of the Chart, which means that the last Chart gets affected only no matter which Chart's legend I click. Here's the code:
jQuery(document).ready(function($) {
if ($(".stats-content__chart__embed").length) {
var chartCount = $(".stats-content__chart__embed").length;
var chartCounter = 1;
window.toggleVisibility = function(element) {
$(element).toggleClass("striken");
}
while (chartCounter <= chartCount) {
var statsChartOptions = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
stepSize: 1000
}
}]
},
legendCallback: function(chart) {
var legendHtml = [];
for (var i = 0; i < chart.data.datasets.length; i++) {
if (chart.data.datasets[i].label) {
legendHtml.push('<li class="stats-content__chart__legend__item" onclick="toggleVisibility(this); updateDataset(event, ' + '\'' + chart.legend.legendItems[i].datasetIndex + '\'' + ')"><span>' + chart.data.datasets[i].label + '</span></li>');
}
}
return legendHtml.join("");
},
legend: {
display: false
}
};
// You can ignore this
if ($(".stats-content").eq(chartCounter - 1).find(".stats-content__chart__datasets").length) {
var chartDatasets = $(".stats-content").eq(chartCounter - 1).find(".stats-content__chart__datasets");
var datasetsCount = chartDatasets.length;
var datasetsArray = [];
var datasetsLineColors = ["rgb(0,42,72)", "rgb(0,174,239)"];
for (var i = 0; i < datasetsCount; i++) {
var dataEntry = chartDatasets.eq(i).find("span").length;
var datasetLineColor;
var dataArrayString = [];
for (var x = 0; x < dataEntry; x++) {
var dataValue = chartDatasets.eq(i).find("span").eq(x).text();
dataArrayString.push(dataValue);
var dataArrayNumbers = dataArrayString.map(Number);
}
if ($(this).find("h6").length) {
var datasetLabel = chartDatasets.eq(i).find("h6").text();
}
if (i % 2 == 0) {
datasetLineColor = datasetsLineColors[0];
} else {
datasetLineColor = datasetsLineColors[1];
}
datasetsArray.push({
label: datasetLabel,
backgroundColor: "transparent",
lineTension: 0,
pointBackgroundColor: "transparent",
pointBorderColor: "transparent",
borderColor: datasetLineColor,
data: dataArrayNumbers,
borderWidth: 2
});
}
}
if ($(".stats-content").eq(chartCounter - 1).find(".stats-content__chart__labels > span").length) {
var chartDatasetLabels = $(".stats-content").eq(chartCounter - 1).find(".stats-content__chart__labels > span");
var labelCount = chartDatasetLabels.length;
var labelsArray = [];
for (var i = 0; i < labelCount; i++) {
var labelText = chartDatasetLabels.eq(i).text();
labelsArray.push(labelText);
}
}
// Ignore all the way to here
var ctx = document.getElementById("stats-content__chart__embed-" + chartCounter).getContext("2d");
window.statsChart = new Chart(ctx, {
type: 'line',
data: {
labels: labelsArray,
datasets: datasetsArray
},
options: statsChartOptions
});
updateDataset = function(e, datasetIndex) {
var index = datasetIndex;
var ci = e.view.statsChart;
var meta = ci.getDatasetMeta(index);
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
ci.update();
};
document.getElementById("stats-content__chart__legend-" + chartCounter).innerHTML = window.statsChart.generateLegend();
chartCounter++;
}
}
});
You can ignore the code that I've put inside comments since that's not relevant to the issue (I've gotten comments that it's too big of a chunk of code so I try to lessen the strain on you guys haha). Please, offer me any type of help. I really need it. Here's also the HTML for it, in case it helps in any way (the actual content is generated dynamically through Wordpress' Advanced Custom Fields plugin).
<?php if ( have_rows( 'stats_tabs' ) ) : ?>
<div id="statsTabContent" class="tab-content stats-holder">
<?php while ( have_rows( 'stats_tabs' ) ) : the_row();
$index = get_row_index(); ?>
<div class="tab-pane fade <?php echo ( $index == 1 ) ? 'in active' : '' ?> stats-content" id="tab-<?php echo $index; ?>">
<ul id="stats-content__chart__legend-<?php echo $index; ?>" class="stats-content__chart__legend"></ul>
<div class="stats-content__description">
<?php the_sub_field( 'tab_description' ); ?>
</div>
<div class="stats-content__chart__holder">
<?php if ( have_rows( 'tab_dataset' ) ) :
while ( have_rows( 'tab_dataset' ) ) : the_row(); ?>
<div class="stats-content__chart__datasets">
<h6><?php the_sub_field( 'dataset_label' ); ?></h6>
<?php if ( have_rows( 'dataset_data' ) ) :
while ( have_rows( 'dataset_data' ) ) : the_row(); ?>
<span><?php the_sub_field( 'dataset_value' ); ?></span>
<?php endwhile;
endif; ?>
</div>
<?php endwhile;
endif; ?>
<div class="stats-content__chart__labels">
<?php if ( have_rows( 'tab_labels' ) ) :
while ( have_rows( 'tab_labels' ) ) : the_row(); ?>
<span><?php the_sub_field( 'tab_label' ); ?></span>
<?php endwhile;
endif; ?>
</div>
</div>
<div class="stats-content__chart">
<canvas id="stats-content__chart__embed-<?php echo $index; ?>" class="stats-content__chart__embed"></canvas>
</div>
</div>
<?php endwhile; ?>
</div>
<?php endif; ?>
You are replacing your variable on each iteration, so naturally the variable refers to the last thing assigned (i.e. the last chart created):
while (chartCounter <= chartCount) {
...
window.statsChart = new Chart(ctx, {...});
...
}
Clicking a legend item calls updateDataset wherein you reference back to window.statsChart via the line:
var ci = e.view.statsChart;
Since statsChart is assigned to the last chart iterated your code affects only that chart.
Either make statsChart an array and pass the relevant index via onclick or simply pass the chart object itself to updateDataset (although that won't work via the inline onclick; you'd need to bind to the element).
I am fetching data from a MySQL database using AJAX/jQuery and then doing some calculations (distance between co-ordinates) on client-side. I found that this is quite taxing on the browser and would like to rather do this on the server-side.
My returned JSON data looks like this:
{
"result": [
["148", "osmand", "2", "2016-03-26 13:48:04", "2016-03-26 13:48:01", "2016-03-26 13:48:01", "1", "-39.094856", "46.166472", "1432.7", "0", "0", "20 Maretha street", "{\"battery\":\"0\",\"ip\":\"105.5.117.20\"}"],
["149", "osmand", "2", "2016-03-26 13:48:24", "2016-03-26 13:48:22", "2016-03-26 13:48:22", "1", "-39.099305", "46.162392", "1435.26", "0", "0", "7 Ernst street", "{\"battery\":\"0\",\"ip\":\"105.5.117.20\"}"],
["150", "osmand", "2", "2016-03-26 13:48:45", "2016-03-26 13:48:43", "2016-03-26 13:48:43", "1", "-39.099305", "46.162392", "1435.62", "0", "0", "7 Ernst street", "{\"battery\":\"0\",\"ip\":\"105.5.117.20\"}"],
],
"errors": false
}
The seventh and eighth values are the co-ordinates. I am currently calculating the distance by plotting the co-ordinates and then drawing a polyline and then calculating the distance of the polyline in leaflet.
I however found some sample PHP code that calculates distance between two points:
class test {
public function GetDistance($lat1, $lng1, $lat2, $lng2) {
$radLat1 = $lat1*3.1415926535898/180.0;
$radLat2 = $lat2*3.1415926535898/180.0;
$a = $radLat1 - $radLat2;
$b = ($lng1*3.1415926535898/180.0) - ($lng2*3.1415926535898/180.0);
$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
$s = $s * 6378.137; // EARTH_RADIUS;
$s = round($s * 1000,3);
return $s;
}
}
usage example
$obj=new test();
$dis=$obj->GetDistance($lat1,$lon1,$lat2,$lon2);
My PHP code currently looks like this:
<?php
$inputvalues = $_POST;
$errors = false;
$result = false;
include_once 'database.php';
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$addresult = "
SELECT * FROM positions WHERE `fixtime` BETWEEN '" . $inputvalues['start'] . "' AND '" . $inputvalues['end'] . "' AND deviceid='" . $inputvalues['deviceid'] . "'
";
if( $result = $mysqli->query($addresult) ) {
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
How can I implement this into my code? I don't know how to get the co-ordinates from the mysql result, do the calculation for each co-ordinate and then output it via JSON.
Sorry if this is a basic or broad question, I am very new to PHP and i'm still learning.
This is my function which save results in intermediate files. I am not sure if it will work for you but could be helpful. Update MY_KEY and mode for use.
function get_distance($locations, $locs){
$location_distance = array();
foreach($locations as $location_key=>$location){
$locs_keys = array_keys($locs);
$loc_lat_lng = "$location[1],$location[2]";
$locs_lat_lng = join('|',$locs_keys);
$path = './'.$location_key;
if(!file_exists($path)){
$path = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=$loc_lat_lng&destinations=$locs_lat_lng&mode=walking&key=MY_KEY";
}
$map_data = file_get_contents($path);
if($path != './'.$location_key){
file_put_contents('./'.$location_key, $map_data);
}
$map_data = json_decode($map_data, true);
$distance = reslove_distance($map_data);
for($i = 0 ; $i < count($distance); $i++){
$location_distance[$location_key][$locs_keys[$i]] = $distance[$i];
}
}
return $location_distance;
}
function reslove_distance($map_data=null){
$distance = array();
foreach($map_data['rows'][0]['elements'] as $element){
$distance[] = (int)$element['distance']['value'];
}
return $distance;
}
Maybe something like this:
function getDistance($lat1, $lng1, $lat2, $lng2, $distance_unit = 'km')
{
$multiplicator = ($distance_unit == 'km' ? 6371 : 3959);
$lat1_rad = deg2rad($lat1);
$lng1_rad = deg2rad($lng1);
$lat2_rad = deg2rad($lat2);
$lng2_rad = deg2rad($lng2);
return $multiplicator * acos(cos($lat1_rad) * cos($lat2_rad) * cos($lng2 - $lng1) + sin($lat1_rad) * sin($lat2));
}
And then when you're fetching the results from database:
$entries = $result->fetch_all();
foreach ($entries as $index => &$entry) {
if ($index < count($entries)) {
$next = $entries[$index + 1];
$entry['distance'] = self::getDistance($entry['latitude'], $entry['longitude'], $next['latitude'], $next['longitude']);
} else {
$entry['distance'] = 0; // there is no "next" point to calculate the distance.
}
}
This should give you an array where each entry contains the distance to the next point
Let me try with my case
$myLoc = ["X", -7.699362, 112.973617, "origin"];
$otherLoc = [
["A", -7.683493, 112.958725, "empty"],
["B", -7.679341, 112.976363, "full"],
["C", -7.702259, 112.983058, "full"],
["D", -7.689507, 113.011858, "empty"],
["E", -7.723439, 112.969114, "empty"],
["F", -7.693207, 112.938988, "full"]
];
function distance($myLoc, $otherLoc)
{
$theta = array();
$dist = array();
$km = array();
for ($i = 0; $i < count($otherLoc); $i++) {
if (($myLoc[1] == $otherLoc[$i][1]) && ($myLoc[2] == $otherLoc[$i][2])) {
return 0;
}
$theta[] = $myLoc[2] - $otherLoc[$i][2];
$dist[] = sin(deg2rad($myLoc[1])) * sin(deg2rad($otherLoc[$i][1])) + cos(deg2rad($myLoc[1])) * cos(deg2rad($otherLoc[$i][1])) * cos(deg2rad($theta[$i]));
$dist_a[] = acos($dist[$i]);
$dist_b[] = rad2deg($dist_a[$i]);
$km[] = round(($dist_b[$i] * 60 * 1.1515) * 1.609344, 1);
}
return $km;
}
$result = distance($myLoc, $fullStatus);
// sort($result);
var_dump($result);
You just need it hehehe
I want to get data from Google calendar to make Chart how much you are at work.
My problem is that i cant load data from PHP to JS -> $DataJSON cant be load by JS...Final script should count how many hours you spend at meetings etc.. There is code
<?php
require_once 'google-api-php-client/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->addScope("https://www.googleapis.com/auth/calendar");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
?>
<form action="" method="POST" enctype="multipart/form-data">
<?php
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo '<input type="checkbox" value='.$calendarListEntry->id.' name="zasedacky[]">' .$calendarListEntry->getSummary()."</br>";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
<select name="type">
<option value="column">Column</option>
<option value="bar">Bar</option>
<option value="area">Area</option>
</select>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$type = $_POST['type'];
$zst = $_POST['zasedacky'];
if(empty($zst))
{
echo("Nevybrali jste žádnou zasedací místnost.");
}
else
{
$N = count($zst);
$data_points = array();
for($i=0; $i < $N; $i++)
{
$calendar = $service->calendars->get($zst[$i]);
$calendarJSON = array("label" => $calendar->getSummary(), "y" => "11");
array_push($data_points, $calendarJSON);
}
$dataJSON = json_encode($data_points, JSON_NUMERIC_CHECK);
echo $dataJSON;
}
}
?>
<script>
$(document).ready(function () {
var dataPoints = <?=$dataJSON ?>;
for(var i = 0; i <= result.length-1; i++)
{
dataPoints.push({label: result[i].label, y: parseInt(result[i].y)});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
document.write(dataPoints);
});
</script>
</body>
<?php
} else {
$redirect_uri = 'http://localhost/calendar/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Thanks for your help
It seems you forgot to define the result variable. Maybe you intended to do this:
<script>
$(document).ready(function () {
var result = <?=$dataJSON ?>;
var dataPoints = [];
for(var i = 0; i <= result.length-1; i++)
{
dataPoints.push({label: result[i].label, y: parseInt(result[i].y)});
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
</script>
Hardcoded data format you provided seems to work fine. Here is the JSFiddle
I just want to ask if how to merge this two array from all id value and data-rate value on my list order? there is too many ul li, so i need to get them all and store it into array.
this is my code in javascript:
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("ul.reorder-photos-list li").each(function() { x.push($(this).attr('data-rate').substr(9)); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {
ids: " " + h + "",
rate: " " + x + ""
},
success: function(html)
{
window.location.reload();
/*$("#reorder-helper").html( "Reorder Completed - Image reorder have been successfully completed. Please reload the page for testing the reorder." ).removeClass('light_box').addClass('notice notice_success');
$('.reorder_link').html('reorder photos');
$('.reorder_link').attr("id","");*/
}
});
and this is my html code:
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?= $row['rate']?>" data-rate="<?php echo $row['rate']; ?>" >
and then in my order_update.php this is my code.
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n], "data" => $rates[$n]);
$n++;
}
and this is my insert query from orderArray
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$update = mysqli_query($this->connect,"UPDATE `test` SET `order` = $count, `rate`=$array[rate] WHERE id = $array[id]");
$count ++;
}
return true;
}
hope someones helps me. :)thanks in advance!
When setting up your data, you don't need to have multiple loops. You can loop through the data once:
var dataArray = [];
$("ul.reorder-photos-list li").each(function() {
var el = $(this),
input = el.children(':input'); // This gets the input decendent of the li
// When adding one item at a time to an array, array[array.length] = item is better
dataArray[dataArray.length] = {
id: el.attr('id').substr(9),
rate: input.val(),
};
});
$.ajax({
type: "POST",
url: "order_update.php",
data: { items: dataArray }, // items gives the PHP something to use as a key in the POST data
success: function(html) {...}
});
Your PHP will look like this:
// The data passed from the Ajax call is already an array
$itemsArray = $_POST['items'];
// Your function to process the array
function updateOrder($orderArray) {
foreach ($orderArray as $index => $array) {
// $index will already have a count, you need to +1 because it's 0-based
mysqli_query($this->connect, "UPDATE `test` SET `order` = " . ($index + 1) . ", `rate`=" . $array['rate'] . " WHERE id = " . $array['id']);
}
return true;
}
var rates;
$("ul.reorder-photos-list li").each(function() {
rates.id.push($(this).attr('id').substr(9));
rates.rate.push($(this).attr('data-rate').substr(9));
});
This will create your JSON object of h/x pairs.
$.ajax({
type: "POST"
, url: "order_update.php"
, data: { JSON.stringify(rates); }
, success: function(html) {
window.location.reload();
/* $("#reorder-helper").html(
* "Reorder Completed - Image reorder have been successfully completed.
* Please reload the page for testing the reorder."
* ).removeClass('light_box').addClass('notice notice_success');
* $('.reorder_link').html('reorder photos');
* $('.reorder_link').attr("id","");
*/
}
});
This should fix your call to send the correct data.
Your PHP side is going to want to have something similar to this:
if(isset($_POST['rates'])) {
$ratesString = $_POST['rates'];
$rates = json_decode($ratesString);
}
// Do other things with $hx`
Your insert query is off, too. You need to declare each value as a variable or your compiler is going to hate your PHP, too. You also have some unnecessary quotes in your query.
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
$rate = $array['rate'];
$id = $array['id'];
mysqli_query($this->connect,"UPDATE test SET order = $count, rate = '$rate' WHERE id = '$id'");
$count ++;
}
return true;
}
For your HTML, I think this is what you were going for, but not sure since it's not really explained all that well...Feel free to comment on your intentions.
<ul>
<?php foreach($orderArray as $array) : ?>
<li id="image_li_<?php echo $array['id']; ?>" class="ui-sortable-handle">
<input id="rate" type="text" value="<?php echo $array['rate']?>" data-rate="<?php echo $array['rate']; ?>" ></li>
<?php endforeach; ?>
</ul>
Hope this helps.
-C§
I got the code now. thanks for your help guys!
var h = [];
$("ul.reorder-photos-list li").each(function() { h.push($(this).attr('id').substr(9)); });
var x = [];
$("input").each(function() { x.push($(this).val()); });
$.ajax({
type: "POST",
url: "order_update.php",
data: {ids: " " + h + "",rate: " " + x + ""},
/*data: { items: dataArray },*/
success: function(html)
{
...
}
});
In Php side:
$idArray = explode(",",$_POST['ids']);
$rateArray = explode(",",$_POST['rate']);
$ids = array();
foreach ($idArray as $id) {
$ids[] = $id;
}
$rates = array();
foreach ($rateArray as $rate) {
$rates[] = $rate;
}
$n = 0;
$orderArray = array();
while( $n <= count($idArray) )
{
$orderArray[] = array("id" => $ids[$n] , "rate" => $rates[$n]);
$n++;
}
$db->updateOrder($orderArray);
function updateOrder($orderArray){
$count = 1;
foreach ($orderArray as $array){
mysqli_query($this->connect, "UPDATE `test` SET `morder` = " . $count . ", `mtoursrate`=" . $array['rate'] . " WHERE id = " . $array['id']);
$count ++;
}
return true;
}
I have created a custom options image switcher for Magento, script compares value from options in drop-down with all image names related to product, and finds the most similar one, you can see an example here
The problem is how to add the "selected" option image to the cart, or better to say how to apply that image instead of the default thumbnail in the cart?
anyway here is the complete code - maybe someone can even find this part useful :)
<?php
// load all images related to product
$product = $this->getProduct();
$galleryData = $product->getData('media_gallery');
$images_array = array();
foreach ($galleryData['images'] as $image) {
array_push($images_array, $image['file']);
}?>
<?php
$colour_select_id = '';
$custom_options_arr = array();
foreach ($_options as $_option) {
if ($_option->getTitle() == 'Helmet Color/Design' || $_option->getTitle() == 'Color') {
$colour_select_id = 'select_' . $_option->getId();
$values = $_option->getValues();
foreach ($values as $value) {
$current_option = ($value->getData());
$custom_options_arr[$current_option['option_type_id']] = $current_option['title'];
}
}
}
// $custom_options_arr now holds key=>value pairs of option_type_id => title
$custom_images_to_output = array();
foreach ($custom_options_arr as $key => $value) {
$best_match = $images_array[0];
for ($i = 1; $i < count($images_array); $i++) {
if (similar_text(strtoupper($images_array[$i]), strtoupper($value)) > similar_text(strtoupper($best_match), strtoupper($value))) {
$best_match = $images_array[$i];
}
}
$custom_images_to_output[$key] = $best_match;
}
$base_url = Mage::getBaseUrl('media') . 'catalog/product';
?>
<?php if ($colour_select_id) { ?>
<script type="text/javascript">
jQuery(document).ready(function() {
var opt_object = <?php echo json_encode($custom_images_to_output); ?>;
var base_path = '<?= $base_url;?>';
jQuery("#<?= $colour_select_id ?>").change(function() {
var optionValue = jQuery(this).attr('value');
if (optionValue) {
var optionValueText = jQuery.trim(jQuery('#<?= $colour_select_id ?> :selected').text());
if (opt_object.hasOwnProperty(optionValue)) {
optionValueText = opt_object[optionValue];
}
jQuery("#image").fadeOut(function() {
jQuery(this).load(function() {
jQuery(this).fadeIn(); });
jQuery(this).attr("src", base_path + optionValueText);
jQuery('#image-zoom').attr("href", base_path + optionValueText);
});
}
});
});
</script>