PHP - Detect change on string - php

I have an array which i do a foreach($array as $key => $value)
in my $key i get
name[1][1]
name[1][2]
name[1][3]
name[2][1]
name[2][2]
how can I add detect when the first index changes from [1][3]->[2][1]
any help is appreciated.
What i want to achieve is this:
<h4>Header</h4>
name[1][1]
name[1][2]
name[1][3]
<h4>Header</h4>
name[2][1]
name[2][2]
<h4>Header</h4>
name[3][1]
name[3][2]
name[3][3]
name[3][4]

Don't know if it is the best option, but this is how i managed to do it.
<?php $k = 1; $flag1 = 0; $flag2 = 1;foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<?php
$endpos = strpos($option_name,']');
$asd = substr($option_name,5,$endpos-5);
$this->firephp->log($asd);
if($asd % 2)
{
if($flag1 === 0)
{
echo ' <h4>Header '. $k .'</h4>';
$flag1 = 1;
$flag2 = 0;
$k++;
}
}
else
{
if($flag2 === 0)
{
echo ' <h4>Header '. $k. '</h4>';
$flag2 = 1;
$flag1 = 0;
$k++;
}
}
?>

You can try like
foreach($name as $parent_key => $parent_value){
echo "<h4>Header</h4><br/>";
foreach($name[$parent_key] as $key=>$value)
{
echo $name[$i][$key]."<br/>";
}
}

foreach($array as $key => $value){
$valuevalues = array();
foreach($value as $val){
if($val != "" && !isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "different-than-previous";
if(!isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "equal-to-first-value";
}
}

Related

How to limit array in array

I want to limit every array to strings with 15 characters or less. I have tried this code, but it does not work:
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
foreach ($a as $values) {
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
My expected output is like this:
1. Dewa,Aditya,
2. Brian,
Every time you go to the next name, you need to reset result_shortdes to count the name length again, place the variable inside the first loop like this:
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
}
you can use $result_shortdes for length and $result to store result like below
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
$result = [];
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}else{
$result[] = $result_shortdes;
break;
}
}
}
echo '<pre>';
print_r($result);
echo '<pre>';

PHP How to merge array element with next while maintaining order?

$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);

How can I add format_number to my code

I am trying to display a number that has the english comma separation.
This code gets the number of likes from multiple pages and displays them in a list ordered by number of facebook likes.
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);
}
return $likes;
}
$array = array("URL HERE","URL HERE");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
$english_format_number = number_format($likes, 'likes');
foreach ($likes as $key => $val) {
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $val['likes'] . "</div></div></li><br />";
}
The code works fine, by the way I am not a coder, and am only just getting into it.
I was trying to add in something like
$english_format_number = number_format($likes, 'likes');
But of course I have no idea if I can do that or where to put it.
Can anyone help?
you use wrong parameter in number_format function. the correct format is number_format(number,decimals,decimalpoint,separator). so change you code to
$english_format_number = number_format($likes, 0, ',', '.') . 'likes';

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

need help with php loop logic

This code works perfectly except that it doesn't print the last 2 rows of my csv file:
This is the file:
603629,0,ATLV0008,"Vendor1",1942.60,11/04/2010,1942.60,9/1-9/30/10,EFT-JP
603627,2,ATLV0008,"Vendor1",1242.40,11/04/2010,1242.40,7/1-7/31/10,EFT-JP
600023,0,FLD4V0003,"Vendor2",1950.00,06/15/2010,1950.00,6/14/10 Request,EFT-JP
600024,0,FLD4V0003,"Vendor2",1800.00,06/15/2010,1800.00,6/14/10 Request,EFT-JP
603631,0,ATLV5066,"Vendor2",1000.00,11/09/2010,1000.00,11/4/10 Check Request,PM2
603647,0,ATLV5027,"DVendor3",2799.80,11/15/2010,2799.80,10/1-10/31/10 Bishop,PM2
603642,5,ATLV5027,"Vendor3",482.40,11/15/2010,482.40,10/1-10/18/10 Allen,PM2
603653,0,ATLV0403,"Vendor4",931.21,11/17/2010,931.21,9/1-9/30/10,EFT-JP
603661,0,ATLV0105,"Vendor5",26.75,11/19/2010,26.75,093139,PM2
603660,1,ATLV0105,"Vendor5",5.35,11/19/2010,5.35,093472,PM2
Here is the code: (It needs to display the sum of 2 rows with the same vendor before the actual rows)
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1000, ","))) {
foreach ($row_array as $key => $val) {
$row_array[$key] = trim(str_replace('"', '', $val));
ob_flush();
}
$complete[] = $row_array;
ob_flush();
}
}
flush();
$prevVendor = '';
$sum = 0;
$venData = '';
if (isset($complete)) {
foreach ($complete as $key => $val) {
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != NULL){
print "<br/>";
print $sum . "<br/>";
print $venData;
$sum = 0; $venData = '';
}
}
foreach ($val as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . '&nbsp';
$prevVendor = $val[3];
}
}
if ($currVendor == $prevVendor){
$sum += $complete[$key][6];
}
}
}
I don't really understand your problem but if you want to get (and save it wherever you want) the sum of each vendors, you should do something like this :
$prevVendor = null;
$venData = '';
$sums = array();
if (isset($complete) && is_array($complete)) {
$lim = count($complete);
for ($key=0;$key<$lim;++$key) { // no need foreach for simple array
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != null){
print "<br/>";
print $venData;
}
$venData = '';
$prevVendor = $currVendor;
$sums[$currVendor] = 0; // set the counter to 0
}
foreach ($complete[$key] as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . ' '; // is useful for you I guess
}
}
$sums[$currVendor] += $complete[$key][6]; // add amounts
}
}
if ($prevVendor != null){ // you need to do this to display the last record
print "<br/>";
print $venData;
}
var_export($sums); // check results
This can be some syntax errors ...

Categories