Nested foreach loop displaying duplicate results php - php

I have function that is supposed to match arrays together using the array_intersect function. I'm trying to match a product name with possible offers with same name from multiple merchants. My issue now is I'm using nested foreach loops and whenever I run it, the loop is always infinite and it prints duplicate results.
Here's the function:
function get_matching_product3(&$catalogue, $stock) {
$stockSmallCase = array_map('strtolower', $stock);
$catalogueSmallCase = array_map('strtolower', $catalogue);
foreach ($catalogueSmallCase as $key => $value)
{
$catalogueKey = $key;
$catalogueValue = $value;
$catalogueTokens = explode (' ', $catalogueValue);
foreach ($stockSmallCase as $key => $value) {
$stockKey = $key;
$stockValue = $value;
$stockTokens = explode (' ', $stockValue);
$match= array_intersect($stockTokens, $catalogueTokens);
$m = count($match);
$t = count($catalogueTokens);
//echo $m;
//echo $t;
if (($m > 1) && (($m / $t) * 100) >= 90) {
//print_r($match);
echo = $catalogueKey." ".$stockKey;
//echo "</br>";
//echo $stockKey;
}
}
}
return null;
}

You have
foreach ($catalogueSmallCase as $key => $value)
and
foreach ($stockSmallCase as $key => $value)
I think the problem came from the $key and $value variables. They are probably misunderstood by php at some time of the loop.
Try changing it in order to différenciates it.

Related

How to convert $x['a']['b']['c'] = d to $x['a.b.c'] = d easily

I have a multiple level array field need to be submit via a form. Not sure what will be the easiest solution:
As php will auto convert dot to underscore, so i change it to array:
$form['a.b_b.c'] ==> <input name="a[b_b][c]" value="$form[a.b_b.c]">
And I got $_POST[a][b_b][c] correctly.
But what is the easiest way to assign this $_POST value back to the original $form['a.b_b.c'] without much loops? eg
$form['a.b_b.c'] = $_POST['a']['b_b']['c'];
Or is there a better way to walk around?
very close to this question but still not yet:
Convert dot syntax like "this.that.other" to multi-dimensional array in PHP
And here is my current solution:
foreach ($form as $k) {
$form[$k] = assign_val($_POST, $k);
}
function assign_val($arr = [], $key = '') {
$keys = explode('.', $key);
$val = &$arr;
foreach ($keys as $k) {
$val = &$val[$k];
}
return $val;
}
I would have a function flatten and do something like:
function flatten($array, $prefix = '') {
$result = array();
foreach($array as $key=>$value) {
if(is_array($value)) {
$result = $result + flatten($value, $prefix . $key . '.');
}
else {
$result[$prefix . $key] = $value;
}
}
return $result;
}
And then you can do:
$form = flatten($_POST);

how to use variable outside foreach loop

How to return $value after loop with its returned data ? I think to create array before loop and equal it to $v to use it after loop but it didn't work.
Any idea on how to solve this problem ?
// create array
$v = array();
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
return $v = $value ;
}
echo $v->country_name
try this:
$v = array();
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
{
if(!in_array($value,$v))
{
array_push($v,$value);
}
}
}
try this
$v = array();
$i=0;
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
$i++;
$v[$i] = $value ;
}
//print $v
print_r($v)
If like using 'return' try this.
$v = iLikeUsingReturn($this,$data);
function iLikeUsingReturn($t,$d){
foreach ($t->json_data->locations as $key => $value) {
if ($value->country_name == $d['city']->country_name)
return $value ;
}
return array();
}
I think the following code will helps you.
// create array
$v = array();
// start loop
foreach ($this->json_data->locations as $key => $value) {
if ($value->country_name == $data['city']->country_name)
// return $value with data
array_push($v, $value);
}
return $v;

PHP - Getting total rows in foreach loop

I'm developing a website and need to get total rows of array in foreach loop.
Here is my code:
$vr = $_GET['vr'];
$dat = file_get_contents("http://example.com"); //this is a datafeed url.
$exp = explode("\n", $dat);
foreach ($exp as $val) {
if($vr == $val) {
// here I have the code if string is found in array. They were found, but I want to get how many were found.
}
I tried the count(); function but it displays 111111111111111111
I know it's possible but I don't know how to make it.
$num = 0;
foreach ($exp as $val) {
if($vr == $val) {
$num++;
}
}
echo $num;

Removing a value from an array php

Is there an easier way to do so?
$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = 21;
$i = 0;
foreach ($array as $value ){
if( $value == $remove)
unset($array[$i])
$i++;
}
//array: 1,57,5,84,8,4,2,8,3,4
The array_search answer is good. You could also arraydiff like this
$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = array(21);
$result = array_diff($array, $remove);
If you want to delete the first occurrence of the item in the array, use array_search to find the index of the item in the array rather than rolling your own loop.
$array = array(1,57,5,84,21,8,4,2,8,3,4);
$remove = 21;
$index = array_search($remove, $array);
if (index !== false)
unset($array[$index]);
To remove all duplicates, rerun the search/delete so long as it finds a match:
while (false !== ($index = array_search($remove, $array))) {
unset($array[$index]);
}
or find all keys for matching values and remove them:
foreach (array_keys($array, $remove) as $key) {
unset($array[$key]);
}
This is a little cleaner:
foreach($array as $key => $value) {
if ($value == $remove) {
unset($array[$key]);
break;
}
}
UPDATE
Alternatively, you can place the non-matching values into a temp array, then reset the original.
$temp = array();
foreach($array as $key => $value) {
if ($value != $remove) {
$temp[$key] = $value;
}
}
$array = $temp;

loop through $_POST variables with similar names

I have several $_POST variables, they are
$_POST['item_number1']
$_POST['item_number2']
and so on
I need to write a loop tha displays the values of all the variables (I don't know how many there are). What would be a simplest way to go about it? Also what would be the simplest way if I do know how many variables I have?
This will echo all POST parameters whose names start with item_number:
foreach($_POST as $k => $v) {
if(strpos($k, 'item_number') === 0) {
echo "$k = $v";
}
}
PHP Manual: foreach(), strpos()
If you know how many do you have:
for ($i=0; $i < $num_of_vars; $i++)
echo $_POST['item_number'.$i]."<br />";
UPDATE:
If not:
foreach($_POST as $k => $v) {
$pos = strpos($k, "item_number");
if($pos === 0)
echo $v."<br />";
}
Gets all POST variables that are like "item_number"
UPD 2: Changed "==" to "===" because of piotrekkr's comment. Thanks
try:
foreach($_POST as $k => $v)
{
if(strpos($k, 'item_number') === 0)
{
echo "$k = $v";
}
}
In the above example, $k will be the array key and $v would be the value.
if you know the number of variables:
<?php
$n = 25; // the max number of variables
$name = 'item_number'; // the name of variables
for ($i = 1; $i <= $n; $i++) {
if (isset($_POST[$name . $i])) {
echo $_POST[$name . $i];
}
}
if you don't know the number:
<?php
$name = 'item_number';
foreach ($_POST as $key) {
if (strpos($key, $name) > 0) {
echo $_POST[$key];
}
}
If you must stick with those variable names like item_numberX
foreach (array_intersect_key($_POST, preg_grep('#^item_number\d+$#D', array_keys($_POST))) as $k => $v) {
echo "$k $v \n";
}
or
foreach (new RegexIterator(new ArrayIterator($_POST), '#^a\d+$#D', null, RegexIterator::USE_KEY) as $k => $v) {
echo "$k $v \n";
}
Better to use php's input variable array feature, if you can control the input names.
<input name="item_number[]">
<input name="item_number[]">
<input name="item_number[]">
then php processes it into an array for you.
print_r($_POST['item_number']);
foreach($_POST as $k => $v) {
if(preg_match("#item_number([0-9]+)#si", $k, $keyMatch)) {
$number = $keyMatch[1];
// ...
}
}
try:
while (list($key,$value) = each($_POST))
${$key} = trim($value);

Categories