I can't remove an item from query result array in php + codeigniter.
This is my code
if($query->num_rows > 0)
{
$rows = $query->result();
foreach ($rows as $key => $row)
{
$i = 0;
$fornecedor = $row->fornecedor;
$marca = $row->marca;
$modelo = $row->modelo;
$versao = $row->versao;
$preco = $row->preco;
foreach ($rows as $row2)
{
$fornecedor2 = $row2->fornecedor;
$marca2 = $row2->marca;
$modelo2 = $row2->modelo;
$versao2 = $row2->versao;
$preco2 = $row2->preco;
if(($fornecedor == $fornecedor2) && ($marca == $marca2) && ($modelo == $modelo2) && ($versao == $versao2) && ($preco == $preco2))
{
$i++;
}
}
if($i > 3)
{
unset($row[$key]);
}
}
return $query;
}
I already checked some examples here in stackoverflow but i cant make this work.
I can't see the problem ty
so $row is a $rows[$key], maybe i don't understand something, but it's seems to me you have to write unset($rows[$key]);
Related
I know the title isn't that good, BUT I really don't know how to describe it in one setence and I need help.
Currently I have this type of disastrous code that count every $type of product there is in the DB (I have 20-30 types, not 2 only):
$cong = 0;
$refr = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
if ($arr[$t]['product_type'] == 'Congélateur') {
$cong += 1;
}
if ($arr[$t]['product_type'] == 'Réfrigérateur') {
$refr += 1;
}
$t++;
}
}
And I do stuff with it after. But I was disgusted to see that code, so I tried to minimize it, but I can't figure it out, I tried that:
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 1;
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n++;
}
}
$t++;
}
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>
Output:
cong=9
refr=1
What we should expect regarding the DB (In the database, there's 2 cong and 6 refr):
cong=2
refr=6
Any sugestion? Thank you!
You're really making this more complicated than it needs to be. Variable variables are almost never the solution and can always be replaced with an array.
The code you're working with makes no sense, why is it assigning $row to another array and then using a counter to access it? The answer you accepted includes 4 loops, one of them nested.
if (mysqli_num_rows($result) === 0) {
// always exit early rather than indent yourself to death
return false;
}
while ($row = mysqli_fetch_assoc($result)) {
$type = $row["product_type"];
$counts[$type] = ($counts[$type] ?? 0) + 1;
}
print_r($counts);
Demo: https://3v4l.org/8cuis#focus=7.3.28
Counters (which count the type names in your example) should be initialised to 0 not to 1.
You also need to increment $$type_n2 in DB read loop. I'd avoid variable variables if possible.
<php?
$t = 0;
$type = array(
"cong" => "Congélateur",
"refr" => "Réfrigérateur",
);
extract($type, EXTR_PREFIX_SAME, "");
if (mysqli_num_rows($result) > 0) {
foreach ($type as $type_n => $type_m) {
$$type_n = 0;
}
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
foreach ($type as $type_n2 => $type_m2) {
if ($arr[$t]['product_type'] == $type_m2) {
$$type_n2++; // not $$type_n
}
}
$t++;
}
foreach ($type as $type_n => $type_m) {
echo $type_n . "=" . $$type_n . "<br>";
}
}
?>
I update my code from PHP 5 to PHP 7 and i got problem with foreach loop. I loocked wor answers here, but none is working. Or i dont understand where i have problem
function getStructure($pid = 0, $expand = array(), $alevel = 0)
{
$struct = array();
if ( $alevel > $this->levelCount) $this->levelCount = (int)$alevel;
$str = $this->dbStructure->getStructure($pid);
foreach ($str as &$row)
{
if ($row["type"] == STRUCT_PAGE)
{
$row["editLink"] = "editPage";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_MODULE)
{
$row["editLink"] = "editModule";
$row["target"] = "_self";
}
elseif ($row["type"] == STRUCT_LINK)
{
$row["editLink"] = "editLink";
$row["target"] = "_blank";
}
elseif ($row["type"] == STRUCT_CATALOG)
{
$row["editLink"] = "editCatalog";
$row["target"] = "_self";
}
$row["childrens"] = $this->getStructure((int)$row["id"], $expand, $alevel+1);
if ($row["type"] == STRUCT_CATALOG and isset($row["childrens"][0]["shortcut"]))
{
$row["shortcut"] = $row["childrens"][0]["shortcut"];
$row["target"] = $row["childrens"][0]["type"] == STRUCT_LINK ? "_blank" : "_self";
}
$struct[] = $row;
}
unset($row);
return $struct;
}
All the time $struct is NULL and I need to be multidimensional array
This code by itself is good. Has no problems, only ampersand is not needet. The problem was in different place. Sorry for spam
There are three "BC" in the result_category but I am only getting 1 result. This is for a personality quiz. Please Help. I also tried $query = "SELECT result FROM quiz_map where result_category = 'BC'"; but still, only 1 result is showing.
$result = mysqli_query($link, $query);
$cat_a = $cat_b = $cat_c = $cat_d = $cat_e = 0;
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$cat = $row['category'];
if ($cat == "A") {
$cat_a += 1;
} elseif ($cat == "B") {
$cat_b += 1;
} elseif ($cat == "C") {
$cat_c += 1;
} elseif ($cat == "D") {
$cat_d += 1;
} elseif ($cat == "E") {
$cat_e += 1;
}
}
$array = array('A' => $cat_a, 'B' => $cat_b, 'C' => $cat_c, 'D' => $cat_d, 'E' => $cat_e);
$str = '';
foreach ($array as $i => $value) {
if ($value >= 6) {
$str = $i;
break;
} elseif ($value >= 2) {
$str .= $i;
}
}
$var = sort($array);
$query = "SELECT result FROM quiz_map where result_category = '$str' LIMIT 1";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
echo $row[0];
?>
There's many things wrong with your code!
As pointed by #IsThisJavascript and #Cashbee:
You are executing a query with a LIMIT 1 statement, it will only return one record.
As pointed by myself:
Doing echo $row[0] will have the same result, if you are only echoing the first value of the array you can't expect to have multiples can you?
As pointed by #IsThisJavascript:
You need to loop the results array, like so:
while($row = mysqli_fetch_array($result)){
echo $row['result_category'];
}
Consider switching the query from a '=' to a '%like%' statement, to maximize results if you want to get the values that partionaly cointain the 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
I have 2 nested arrays over which I intent to iterate over one and insert into it a portion of a match in the other based on a key->value.
The idea is to iterate for each element of arrayA and nested iterate for each key->value of arrayB. When arrayA element equals to arrayB key->value i want to insert into arrayB a key->value of arrayA.
The problem I am having is that for some reason in the loop of arrayB it should iterate 78 times but is doing it only 2.
I know there is something messed up with the iterations but can't pin point.
Here is a sample of arrayA, arrayB and my code.
arrayA
arrayB
Here is my code
foreach($premiumContent as $prem_key => $targets)
{
$totCat = 0;
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$totCat = $totCat + 1;
$totFeatures = 0;
foreach($category as $features) //features = 1 designers, restaurants
{
$totFeatures = $totFeatures + 1;
//*********HERE IS THE PROBLEM IS NOT ITERATING BY THE LIST OF ALL FEATURES
$totFeature = 0;
foreach ($features as $feature) //stores
{
$totFeature = $totFeature + 1;
$properties = $feature[0]->properties;
if ($feature[0]->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}
return $result;
Could someone explain me what am I doing wrong? I am sure there is a better approach to this.
Here is the fix.
foreach($result as $category) //(result = 2 shop, ff) (category shop.designers, ff.restaurant)
{
$name = $category->dispName;
//echo $name;
foreach($category->list as $features) //features = 1 designers, restaurants
{
foreach ($features as $featureKey => $featureVal) //stores
{
$properties = $featureVal->properties;
if ($featureVal->id == $prem_key)
{
if(count($targets[media]) > 0)
{
$properties->media = $targets[media];
}
else
{
$properties->media = '';
}
if(count($targets[offer]) > 0)
{
$properties->offer = $targets[offer];
}
else
{
$properties->offer = '';
}
if(count($targets[bi]) > 0)
{
$properties->bi = $targets[bi];
}
else
{
$properties->bi = '';
}
if(count($targets[info]) > 0)
{
$properties->info = $targets[info];
}
else
{
$properties->info = '';
}
}
}
}
}
}