Compare each index in single array - php

I have a function to calculate distance, the data comes from a database.
Here is the code for calculating:
function jarak() {
global $conn;
$query1 = mysqli_query($conn, "SELECT signature, sig_priority FROM centro");
$query2 = mysqli_query($conn, "SELECT signature, sig_priority, status FROM acid_event");
while ($row = mysqli_fetch_array($query1, MYSQLI_ASSOC)) { $master[]=$row; }
while ($row = mysqli_fetch_array($query2, MYSQLI_ASSOC)) { $data[]=$row; }
$jarak = array();
foreach ($data as $key => $val) {
foreach ($master as $key2 => $value) {
$jarak = sprintf("%0.2f",sqrt(pow($val['signature'] - $value['signature'], 2) + pow($val['sig_priority'] - $value['sig_priority'], 2)));
echo "distance from (" . $value['signature'] . "," . $value['sig_priority'] . ") ke (" . $val['signature'] . "," . $val['sig_priority'] . ") is : " . $jarak . "<br>";
$euc[]=$jarak;
}
}
}
And here is the result from that:
Array(
[0] => 30.04
[1] => 0.00
[2] => 30.04
[3] => 0.00
[4] => 47.00
[5] => 17.03
[6] => 5.02
[7] => 25.08
[8] => 2.06
[9] => 32.06
[10] => 37.00
[11] => 7.07 )
I want to compare each 2 index array with greater than or less than.
Example : [0] with [1], [2] with [3], [4] with [5] and so on. It just compare with 2 index.
I tried this but no result
for ($i=0; $i<count($cb); $i++) {
for ($k=0;$k<2;$k++) {
if($cb[$i][$k]<$cb[$i][$k]) {
echo "low";
} elseif ($cb[$i][$k]>$cb[$i][$k]) {
echo "high";
}
}
}
Output I want should look like this
if [0] < [1] then "high" and it loop for other index array like [2] with [3], [4] with [5] and so on.

I think you were quite close to what you wanted to accomplish but it seems like you were making things harder than they needed to be.
Your code is below.
for ($i=0; $i<count($cb); $i++) {
for ($k=0;$k<2;$k++) {
if($cb[$i][$k]<$cb[$i][$k]) {
echo "low";
} elseif ($cb[$i][$k]>$cb[$i][$k]) {
echo "high";
}
}
}
As you can see your if statements are comparing the exact same value to each other, that's not going to do much. But I can see what you were trying to do in the second for loop.
Instead, what we really want to do is move through your array in steps of 2.
for ($i=0; $i<count($cb); $i+=2) {
//stuff
}
This way we can compare the first element and the element after that to each other. Like this:
if($cb[$i] > $cb[$i+1]) {
echo $i . 'is higher than '. $i+1;
} elseif($cb[$i] < $cb[$i+1]) {
echo $i . 'is lower than '. $i+1;
} else {
echo $i . 'is the same as '. $i+1;
}
So all together it would be something like this:
for ($i=0; $i<count($cb); $i+=2) {
if($cb[$i] > $cb[$i+1]) {
echo $i . 'is higher than '. $i+1;
} elseif($cb[$i] < $cb[$i+1]) {
echo $i . 'is lower than '. $i+1;
} else {
echo $i . 'is the same as '. $i+1;
}
}
Now you can change the echo's to whatever you want to do and you should probably add some validation too (like checking if the keys actually exist before accessing them), but this is a good place to get started.

I did a solution, but I decided to keep the response in an array because it makes more sense to me to be able to read this information somewhere else later.
Here's my solution:
$test = array(
30.04,
0.00,
30.04,
0.00,
47.00,
17.03,
5.02,
25.08,
2.06,
32.06,
37.00,
7.07,
);
$output = array();
foreach ($test as $key => $value) {
// To make sure this will only be executed every second item
if ($key % 2 !== 0) {
continue;
}
$next = '';
if (!isset($test[$key+1])) {
break;
} else {
$next = $test[$key+1];
}
$output[$key] = $value . ' is ' . ($value < $next
? "lower"
: ($value > $next
? 'higher'
: 'equal')) . ' than ' . $next;
}
echo '<pre>';
print_r($output);
Here's the code tested: https://3v4l.org/Pg5La

Related

How to echo json_decode array?

I have fetched json data from server and decode using json_decode(value, true);
using print_r function I got this array as output
Array
(
[id] => 120
[key] => 7ca04960a36dbb7f4b7c8607bb3
[num] => 0
)
Array
(
[id] => 121
[key] => 7ca04960a36dccgki49g6dfg57
[num] => 0
)
I want to display decoded data using while loop.
while($row = mysqli_fetch_assoc($result)) {
$json = json_decode($row['post_req'], true);
echo "<pre>";
print_r($json);
echo "</pre>";
}
ex:
id = 120,
key = 7ca04960a36dbb7f4b7c8607bb3,
num = 0
how can I print data ?
Edited: It looks like you changed some details.
It looks like you are getting multiple arrays
$output = array();
while($row = mysqli_fetch_assoc($result)) {
$json = json_decode($row['post_req'], true);
$ouput[] = $json;
}
This will give you a multi-layered array and if you just want the id you can do this
for ($i = 0; $i < sizeof($output); $i++) {
echo "id =" . $output[$i]['id'] . " <br/>";
}
or you can use this to get id only
for ($i = 0; $i < sizeof($output); $i++) {
foreach ( $output[$i] as $key => $value ) {
if ('id' === $key) {
echo "$key = $value <br />";
}
}
}
The expected output is
id = 120
id = 121
If you want all three values use this
for ($i = 0; $i < sizeof($output); $i++) {
foreach ( $output[$i] as $key => $value ) {
echo "$key = $value <br />";
}
}
Expected output
id = 120
key = 7ca04960a36dbb7f4b7c8607bb3
num = 0
id = 121
key = 7ca04960a36dccgki49g6dfg57
num = 0
foreach($json as $key => $value) {
echo "$key: $value \n";
}

How to count/sum this values of the same word in PHP?

I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>

Rank php multidimensional array

I'm trying to rank a group of scores. So I've taken the input from a users form and sorted them from largest to smallest in a multidimensional array, so then that I can search the array for the user and retrieve the index to get its "rank" however I appear to be doing something totally wrong! any help on where I'm going wrong would be greatly appreciated, or if there is a better way entirely!
Thank you
PHP Code:
if ( isset( $_POST['submit'] ) ) {
$size = $num_rows;
$p = 0;
$myarray = array();
while ( $p < $size ) {
$myarray[] = array( "user" => $user[$p], "data" => $scanrate[$p] );
$p++;
}
$sort = array();
foreach ( $myarray as $k => $v ) {
$sort['data'][$k] = $v['data'];
}
array_multisort( $sort['data'], SORT_DESC, $myarray );
for ( $i = 0; $i < $num_rows; $i++ ) {
$key = array_search( $i, array_column( $myarray, 'user' ) );
if ( !$key ) {
$key = $num_rows;
}
//this is stored into my database
echo "<br>User " . $user[$i] . " scan rate " . $scanrate[$i] . " rank " . $key;
}
}
You do useless code to do this sort, use the usort() function like :
while($p < $size)
{
$myarray[] = array("user" => $user[$p], "data" => $scanrate[$p]);
$p++;
}
usort($myarray, function($a, $b) {
return $a['data'] - $b['data'];
});
Now your $myarray is sorted and you can search and do what you want.
If you're putting too much effort on smt. with a scripting language, you're definitely doing it wrong...
$sort = array_combine($user, $scanrate);
asort($sort);
// $sort is sorted now, used it as you like:
// List them
foreach ($sort as $user => $scanrate) {
echo "<br>User " . $user . " scan rate " . $scanrate . " rank " . ++$i;
}
// Find the rank of specific user:
echo array_search('matt', array_keys($sort)) + 1;

loop through array not returning correct values

I've been staring at this for some time, but can't figure out what's wrong. First of all my code:
//Show the products information line by line
$item_count = 0 ;
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
$data2[$i][0] = $order->products[$i]['qty'];
if (strlen($order->products[$i]['name']) > 40 && strlen($order->products[$i]['name']) < 50){
$data2[$i][1] = $order->products[$i]['name'];
} else if (strlen($order->products[$i]['name']) > 50) {
$data2[$i][1] = substr($order->products[$i]['name'],0,50);
} else {
$data2[$i][1] = $order->products[$i]['name'];
}
$data2[$i][2] = $order->products[$i]['model'];
$data2[$i][3] = str_replace(' ', ' ',$currencies->format($order->products[$i]['final_price'], true, $order->info['currency'], $order->info['currency_value']));
// Add to $data2 if needed (adjust/renumber subsequent array keys!):
// For VAT purposes:
// Check if product is an 'electronic service'. If so, determine the customer's country.
// NOTE (Debug): the comparison of " pov.products_options_values_name = $order->products[$i]['attributes'][$j]['value'] " only holds if the option description is not changed/replaced/deleted.
if (isset($order->products[$i]['attributes']) && (($k = sizeof($order->products[$i]['attributes'])) > 0)) {
for ($j = 0; $j < $k; $j++) {
$virtual_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_ATTRIBUTES_DOWNLOAD . " pad, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . $order->products[$i]['id'] . "' and pov.products_options_values_name = '" . $order->products[$i]['attributes'][$j]['value'] . "' and pa.products_attributes_id = pad.products_attributes_id");
$virtual_check = tep_db_fetch_array($virtual_check_query);
if ($virtual_check['total'] > 0) {
$product_type_check = 'virtual';
$order_type_check = 'virtual or mixed';
break;
}
}
}
if ($product_type_check == 'virtual') {
if ($customer_country == 'home country') {
$data2[$i][4] = str_replace(' ', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%');
} elseif ($customer_country == 'eu country') {
$data2[$i][4] = '***';
} else {
$data2[$i][4] = str_replace(' ', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%');
}
} else {
$data2[$i][4] = str_replace(' ', ' ',tep_display_tax_value($order->products[$i]['tax']) . '%');
}
unset($product_type_check);
// $data2[$i][3] = str_replace(' ', ' ',$currencies->format($order->products[$i]['final_price'], true, $order->info['currency'], $order->info['currency_value']));
// Add to $data2 if needed (adjust/renumber subsequent array keys!):
// $data2[$i][5] = str_replace(' ', ' ',$currencies->format(tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']), true, $order->info['currency'], $order->info['currency_value']));
$data2[$i][5] = str_replace(' ', ' ',$currencies->format($order->products[$i]['final_price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value'])) ;
// Add to $data2 if needed (adjust/renumber subsequent array keys!):
// $data2[$i][5] = str_replace(' ', ' ',$currencies->format(tep_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']));
// Show the products attributes
$data3 = array();
//get attribs
if (isset($order->products[$i]['attributes']) && (($z = sizeof($order->products[$i]['attributes'])) > 0)) {
$attribute_line = 'true';
for ($m = 0; $m < $z; $m++) {
if ($order->products[$i]['attributes'][$m]['price'] != '0') {
if (strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'] . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')') > 50) {
$data3[$i][$m][1] = substr('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'],0,40) . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')';
} else {
$data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'] . ' (' . $order->products[$i]['attributes'][$m]['prefix'] . $currencies->format($order->products[$i]['attributes'][$m]['price'] * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ')' ;
}
} else {
if (strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value']) > 50) {
$data3[$i][$m][1] = substr('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'],0,50);
} else {
// $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value'];
$data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value'];
}
}
}
}
}
The code above is supposed to:
Put the general product data into the array $data2
Put the attributes of each product (which can be more than one) into the array $data3
The array $order->products contains the following data:
Array (
[0] => Array (
[qty] => 1
[id] => 4
[name] => Product A
[model] =>
[tax] => 21.0000
[price] => 19.9900
[final_price] => 19.9900
[attributes] => Array (
[0] => Array (
[option] => Type
[value] => X
[prefix] => +
[price] => 0.0000
)
)
)
[1] => Array (
[qty] => 1
[id] => 4
[name] => Product A
[model] =>
[tax] => 21.0000
[price] => 19.9900
[final_price] => 19.9900
[attributes] => Array (
[0] => Array (
[option] => Type
[value] => Y
[prefix] =>
[price] => 0.0000
)
)
)
)
The code enters the following data in the array $data3:
Array (
[1] => Array (
[0] => Array (
[1] => - Y
)
)
)
This means that the attributes of the first product (Product A with key 0 in the $order->products array is missing!
My gut feeling tells me that the code has moved already moved through the $order->products array before executing the 'Show the products attributes' section of the code.
The code is based on this snippet taken from checkout_confirmation.php (osCommerce):
for ($i=0, $n=sizeof($order->products); $i<$n; $i++) {
echo ' <tr>' . "\n" .
' <td class="infoBoxMargin">' . tep_draw_separator('pixel_trans.gif', '10', '1') . '</td>' . "\n" .
' <td class="main" align="left" valign="top" width="10%">' . $order->products[$i]['qty'] . ' x</td>' . "\n" .
' <td class="main" align="left" valign="top" width="60%">' . $order->products[$i]['name'];
if (STOCK_CHECK == 'true') {
echo tep_check_stock($order->products[$i]['id'], $order->products[$i]['qty']);
}
if ( (isset($order->products[$i]['attributes'])) && (sizeof($order->products[$i]['attributes']) > 0) ) {
for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) {
echo '<br /><nobr><small> <i> - ' . $order->products[$i]['attributes'][$j]['option'] . ': ' . $order->products[$i]['attributes'][$j]['value'] . '</i></small></nobr>';
}
}
Can anyone explain to me where things go wrong?
Kind regards,
Dennis
Using your sample data for $order->products, $order->products[$i]['attributes'][$m]['price'] is always zero. Also, since strlen('- ' . $order->products[$i]['attributes'][$m]['option'] . ': ' . $order->products[$i]['attributes'][$m]['value']) is always <50, the only code in the //get attribs section that executes with your sample data is $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value']; ... which is why $data3[$i][$m][1] is the only value that gets populated.
However, assuming your two missing } belong at the end, then $data3 is getting overwritten for every value of $i on account of wher $data3 = array(); is located.
If you move $data3 = array(); to the top of your code (before the for loop), you'll at least no longer overwrite the values in $data3 for each version of your product.
If you want $data3 to contain a copy of every attribute, then try changing $data3[$i][$m][1] = '- ' . $order->products[$i]['attributes'][$m]['value']; to $data3[$i][$m] = $order->products[$i]['attributes'];
#lazy.lizard
It can be that easy ... if you know what you're doing!
The code now starts with:
$data2=array();
$data3 = array();
//Show the products information line by line
$item_count = 0 ;
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
$data2[$i][0] = $order->products[$i]['qty'];
Dealing with osCommerce code for many years I have to say, that there are lots of wierd code and if you are not for long with it, you better migrate to something new, thay doesn't use register_globals al least. Another reason to migrate is that there's no MVC model - you always see mixed php code, html layout and sql queries, especially in admin section. Another important reason for migration is tables structure, or more precisely, lack or wrong indexes.
As for me, I've completely rewritten lots of code, including totally new product class and products attributes. Now, for example, I use product object everywhere, including products list in category, shoping cart, wishlist, etc. Believe me, I don't have a headache with separate sql queries that get different products' data.
Now to you question. I suppose that problem is here:
$data3 = array();
Each time you loop $order->products your variable is set to empty array. Thus try to define it before you start iterating $order->products. For example:
$data3 = array();
for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
// your code
}
and don't forget to remove $data3 = array(); from the loop.
Hope this helps.
Good luck.

To get the multi dimention array values in php

I have a multi-dimension array in php like this
$shop = array(
array("name","point","number"),
array('Ranjit', 1.25 , 15),
array('Pitabas', 0.75 , 25),
array('Khela', 1.15 , 7)
);
Now I have to show the output like this
name-> ranjit
Point-> 1.25
number->15
name->Pitabas
Point->0.75
number->25
name->Khela
Point->1.15
number->7
I am trying for loop, but I could get the result in nested forloop. Please help me to get the answer.
My solution:
$headings = array_shift($shop);
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $headings[$key], '=>', $value;
}
}
Here's a simple loop: Observe that we skip the first element of the outer array, which is deemed to contain the headers:
for ($i = 1; $i != count($shop); ++$i)
{
print $shop[0][0] . ": ". $shop[$i][0] . "\n";
print $shop[0][1] . ": ". $shop[$i][1] . "\n";
print $shop[0][2] . ": ". $shop[$i][2] . "\n";
}
You know the first row will be the titles, so store them separately:
$titles = $shop[0];
That will give you
$titles = array('name', 'point', 'number');
Then loop through your array:
foreach ($shop as $index => $row) {
if ($index == 0)
continue;
foreach($row as $column => $item) {
echo $titles[$column] . " -> " . $item . "<br />";
}
}
This should give the desired output:
for($x = 1, $lim = sizeof($shop); $x < $lim; $x++)
{
echo $shop[0][0]."->".$shop[$x][0]."<br>";
echo $shop[0][1]."->".$shop[$x][1]."<br>";
echo $shop[0][2]."->".$shop[$x][2]."<br>";
}

Categories