Ok so I have an array "$landing" in my header.php, then in my page.php I include the header.php but for some reason when I call the 'Name' field in the array in the page.php: echo $landing['Name']; it just doesn't work.
this is how the array is being filled up, and calling it in the header works perfectly.
$landing = array();
while ($row = mysql_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing = $row;
}
}
To clarify, $row and $landing are both arrays, and both have multiple fields 'Name' 'Color' 'Info'.
What am I doing wrong here? Do I need to make it global somehow or what's going on?
The original code works somehow, now as the OP said in a comment.
But my old tips still hold:
Consider using MySQLi or PDO instead of the deprecated MySQL extension!
Why do you compare the dataset's column value on the client-side? You can do this on the MySQL side, it'll be faster!
You are, as ComFreek correctly stated, turning $landing into a string. Instead, if you're trying to add an entry to the landing array, use [] brackets which mean "add into new entry".
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing[] = $row;
}
}
I cant comment LS97 post, anyway you want to use $landing["Name"] you edit LS97 code into this:
$landing = array();
while ($row = mysqli_fetch_array($result)) {
$str = strtolower($row['Name']);
if ($str == $name) {
$landing["name"] = $row;
}
}
If you want to use multiple names, LS97 code is fine.
The problem is what they said. (Using $landing = $row, landing will be a string.)
Related
I have an small piece of PHP code that needs to put every file in the current directory into an array.
I have done this by making reading the dir with glob() and when it meets another dir it will loop.
My code I have as of now:
<?php
$find = '*';
$result = array();
function find($find)
{
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
find($zoek);
}
}
return $result;
}
print_r(find($find));
?>
When I execute the code the echo print exactly what I want. But the printed array doesn't give me the values I want, it only gives the values in the first dir it will come by then it seems to stop adding the value in the array.
What am I doing wrong?
You need to actually preserve the results you produce in the recursive callings to your function:
<?php
function listNodesInFolder($find) {
$result = [];
foreach (glob($find) as $entry) {
$result[] = $entry;
if (is_dir($entry)) {
$result = array_merge($result, find($entry.'/*'));
}
}
return $result;
}
print_r(find('*'));
Once on it I also fixes a few other issues with your code:
$result should be declared as an array inside your function, that that even if it does not loop you still return an array and not something undefined.
indentation and location of brackets got adjusted to general coding standards, that makes reading your code much easier for others. Get used to those standards, it pays out, you will see.
no need for an extra variable for the search pattern inside the conditional.
a speaking name for the function that tells what it actually does.
you should not name variables and functions alike ("find").
You need to add the result of find() to the array
Edit added array_merge - Cid's idea
<?php
$find = '*';
function find($find)
{
$result = array();
foreach (glob($find) as $entry)
{
$result[] = $entry;
echo $entry.'<br>';
if (is_dir($entry)){
$zoek = ''.$entry.'/*';
$result = array_merge($result, find($zoek));
}
}
return $result;
}
print_r(find($find));
?>
Could anyone help me with such issue:
I'm trying to make thing, that based on $_Post data I'm showing or not data in the Google tables. (I've removed unnecessary parts of code, that are not actual to this question)
currently, check looks like:
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
$t0 = ",'\".";
$t1 = '$row['."'".PM."'".']';
$t2 = ".\"'";
$pm_ent = $t0.$t1.$t2;
}
else
{
$pm = "";
$pm_script = "";
$pm_ent = "";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
So basically, when $_POST is empty, nothing is included (as well in script), and it works pretty fine, as needed.
But I'm not able to make it work, when $_POST is not empty: as far as I was experimenting(this one is my last attempt), it printed in the data table exactly string value of the pm_ent value, so it wasn't working in the code as such but became really as a string.
Maybe someone could help me with this, so it would work dynamically - If it's not empty, PM row would be added to the data Rows? As I'm not so good at PHP, I'm having lack of knowledge, how to solve this...
Or maybe there is some smarter way how to do it?
$pm_script = "";
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
$pm_ent = "";
if( $pm_script !="")
{
$pm_ent =",'".$row['PM']."'";
}
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
Hope it will help..
I'm trying to link the MySQL while loop into foreach loop using something like this :
if($something == true){
foreach($array as $arr){
} else {
while($row = mysql_fetch_array($mysql_query)){
}
// loop instructions
}
It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database
I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :
if($something == true){
$mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
$mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}
while($row = mysql_fetch_array($mysql_query)){
...
That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop
P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above
Put your processing into a function:
function process_data($data) {
// do stuff
}
if($something){
foreach($array as $arr){
process_data($arr);
}
} else {
while($row = mysql_fetch_array($mysql_query)){
process_data($row);
}
}
The other answers here are fine, but you'd be better served just to make sure that $array is a valid array regardless of something ... How about
if (!something){
$array = array();
while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}
foreach($array as $arr){
// do work
}
You'd probably get a better answer if you expanded the scope of what you've explained a bit. Without knowing what the something is and what the data is, plus the ultimate objective then it's hard to tell what kind of structure you should be using.
It seems to me that you could achieve this by just using a function, if the code inside the loop is the same. Like this:
if($something == true)
{
foreach($array as $arr)
{
doWork($arr);
}
}
else
{
while($row = mysql_fetch_array($mysql_query))
{
doWork($row);
}
}
function doWork($arr)
{
//...
}
You cannot nest loop instructions inside a loop like this. You'll need to have two separate loops completely inside the IF statements.
if($something == true){
foreach($array as $arr){
// do work
}
} else {
while($row = mysql_fetch_array($mysql_query)){
// do work
}
}
Maybe you could look at from this viewpoint. And take note that this code uses mysql_fetch_assoc() instead of mysql_fetch_array(). Try both functions and look at the resulting rows with var_dump(). You will see that mysql_fetch_array() has twice as much data. You may want that, but probably not.
if ($something !== true)
{
$array = array();
while($row = mysql_fetch_assoc($mysql_query_result_resource))
{
$array[] = $row;
}
}
foreach($array as $arr)
{
/* PROCESS */
}
TL;DR
I have this data: var_export and print_r.
And I need to narrow it down to: http://pastebin.com/EqwgpgAP ($data['Stock Information:'][0][0]);
How would one achieve it? (dynamically)
I'm working with vTiger 5.4.0 CRM and am looking to implement a function that would return a particular field information based on search criteria.
Well, vTiger is pretty weakly written system, looks and feels old, everything comes out from hundreds of tables with multiple joins (that's actually not that bad) etc., but job is job.
The need arose from getting usageunit picklist from Products module, Stock Information block.
Since there is no such function as getField();, I am looking forward to filter it out from Blocks, that is actually gathering the information about fields also.
getBlocks(); then calls something close to getFields();, that again something close to getValues(); and so on.
So...
$focus = new $currentModule(); // Products
$displayView = getView($focus->mode);
$productsBlocks = getBlocks($currentModule, $displayView, $focus->mode, $focus->column_fields); // in theory, $focus->column_fields should/could be narrowed down to my specific field, but vTiger doesn't work that way
echo "<pre>"; print_r($productsBlocks); echo "</pre>"; // = http://pastebin.com/3iTDUUgw (huge dump)
As you can see, the array under the key [Stock Information:], that actually comes out from translations (yada, yada...), under [0][0] contains information for usageunit.
Now, I was trying to array_filter(); the data out from there, but only thing I've managed to get is $productsBlocks stripped down to only contain [Stock Information:] with all the data:
$getUsageUnit = function($value) use (&$getUsageUnit) {
if(is_array($value)) return array_filter($value, $getUsageUnit);
if($value == 'usageunit') return true;
};
$productsUsageUnit = array_filter($productsBlocks, $getUsageUnit);
echo "<pre>"; print_r($productsUsageUnit); echo "</pre>"; // = http://pastebin.com/LU6VRC4h (not that huge of a dump)
And, the result I'm looking forward to is http://pastebin.com/EqwgpgAP, that I've manually got by print_r($productsUsageUnit['Stock Information:'][0][0]);.
How do I achieve this? (dynamically...)
function helper($data, $query) {
$result = array();
$search = function ($data, &$stack) use(&$search, $query) {
foreach ($data as $entry) {
if (is_array($entry) && $search($entry, $stack) || $entry === $query) {
$stack[] = $entry;
return true;
}
}
return false;
};
foreach ($data as $sub) {
$parentStack = array();
if ($search($sub, $parentStack)) {
$result[] = $parentStack[sizeof($parentStack) - 2];
}
}
return $result;
}
$node = helper($data, 'usageunit');
print_r($node);
I'm new to OOP in PHP, is that to seems correct ?
class whatever {
Function Maths() {
$this->sql->query($requete);
$i = 0;
while($val = mysql_fetch_array($this)) {
$tab[i][average] = $val['average'];
$tab[i][randomData] = $val['sum'];
$i=$i+1;
}
return $tab;
}
I want to access the data contained in the array
$foo = new whatever();
$foo->Maths();
for ($i, $i <= endOfTheArray; i++) {
echo Maths->tab[i][average];
echo Maths->tab[i][randomData];
}
Thank you ;)
EDIT: i want to output the result of the SQL query as an array, so i can access it from outside the class
In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at #webbiedave's link.
class whatever {
static function maths() {
$tabs = array();
$results = $this->sql->query($requete);
while($val = mysql_fetch_array($this)) {
$tabs = $val;
}
return $tabs;
}
This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.
Here are some modifications to how this would be used:
$results = whatever::maths();
foreacho ($results as $result) {
echo $result['average'];
echo $result['randomData'];
}
Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
That convoluted for loop can be replaced with a foreach loop.
Please check out PHP OOP basics:
http://www.php.net/manual/en/language.oop5.basic.php
Edit: Thanks for cleaning up the code. Try something along the lines of:
$tabs = array();
while($val = mysql_fetch_assoc($result)) {
$tabs[] = $val;
}
And:
$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
echo $tab['average'];
echo $tab['randomData'];
}
http://www.php.net/manual/en/language.oop5.basic.php