My objective is to search a multidimentional array for a plot and output information about who is buried there.
My code is
function searchByPlot($plot, $array) {
foreach ($array as $key => $val) {
if ($val['plot'] === $plot) {
return $key;
}
}
return null;
}
function calculate() {
$id = searchByPlot('681', $ma);
$code = $ma[$id]['code'];
$last = $ma[$id]['h_last'];
$plot = $ma[$id]['plot'];
if (isset($last)){
echo 'ID: '.$id.' Code: '.$code.' Lastname'.$last.'';
}
echo "Test".$id."";
}
calculate();
However when i call the calculate function there is no response even though there is a result in the array.
When i call the searchByPlot function directly it works fine.
$id = searchByPlot('681', $ma);
echo $id;
However when i call the calculate function it doesn't work at all, nothing is outputted on $id as you can see my test call above.
echo $id;
Can you help please?
Many thanks, Buster
Related
I'm trying to make a simple template system because I don't want to use Smarty or anything like that.
My current problem is that I can't make 1 tag print every result from a while loop. It only prints the first result.
public $TplKey = array();
public function GetContent($file, $data) {
$template = file_get_contents($file);
foreach($data as $key => $value) {
$template = str_replace('{'.$key.'}', $value, $template);
}
return $template;
}
public function View($file) {
return $this->GetContent($file, $this->TplKey);
}
public function TplKeyAdd($key, $value) {
return $this->TplKey += array($key => $value);
}
public function testing() {
global $DBHandle;
$q = $DBHandle->mysqli->query("SELECT * FROM site_users");
while($qf = $q->fetch_array()) {
$r = $this->TplKeyAdd("var", $qf["user_name"]);
}
return $r;
}
Then, later on in my .TPL file I call {var}. But it only shows the first database row (as stated). I want it to show every row it can find. How can I solve this?
Your issue lies with how you're storing the key => value pairs in the TplKeyAdd method.
I believe you're after:
public function TplKeyAdd($key, $value) {
return $this->TplKey[] = array($key => $value);
}
Also with this:
$this->TplKeyAdd("var", $qf["user_name"]);
The key you're adding every time is called "var" so each value from the database doesn't have it's own key.
Edit: Also as ianinn pointed out, you shouldn't be returning within your while look as it'll only get the first iteration.
I have a question about a recursive PHP function.
I have an array of ID’s and a function, returning an array of „child id’s“ for the given id.
public function getChildId($id) {
…
//do some stuff in db
…
return childids;
}
One childid can have childids, too!
Now, I want to have an recursive function, collecting all the childids.
I have an array with ids like this:
$myIds = array("1111“,"2222“,"3333“,“4444“,…);
and a funktion:
function getAll($myIds) {
}
What I want: I want an array, containing all the id’s (including an unknown level of childids) on the same level of my array. As long as the getChildId($id)-function is returning ID’s…
I started with my function like this:
function getAll($myIds) {
$allIds = $myIds;
foreach($myIds as $mId) {
$childids = getChildId($mId);
foreach($childids as $sId) {
array_push($allIds, $sId);
//here is my problem.
//what do I have to do, to make this function rekursive to
//search for all the childids?
}
}
return $allIds;
}
I tried a lot of things, but nothing worked. Can you help me?
Assuming a flat array as in your example, you simply need to call a function that checks each array element to determine if its an array. If it is, the function calls it itself, if not the array element is appended to a result array. Here's an example:
$foo = array(1,2,3,
array(4,5,
array(6,7,
array(8,9,10)
)
),
11,12
);
$bar = array();
recurse($foo,$bar);
function recurse($a,&$bar){
foreach($a as $e){
if(is_array($e)){
recurse($e,$bar);
}else{
$bar[] = $e;
}
}
}
var_dump($bar);
DEMO
I think this code should do the trick
function getAll($myIds) {
$allIds = Array();
foreach($myIds as $mId) {
array_push($allIds, $mId);
$subids = getSubId($mId);
foreach($subids as $sId) {
$nestedIds = getAll($sId);
$allIds = array_merge($allIds, $nestedIds);
}
}
return $allIds;
}
I couldn't find anything that answers my question so here it is:
I need to have a foreach loop to take each function inside of an array and run each and check if it returns true, simple enough. Like this:
$array_name = array(function1(),function2(),function3());
foreach($array_name as &$value) {
/* run each function */
/* checks if it returns true */
}
This may be so easy I just don't see it, but I can't find any definitive documentation on how to correctly implement this.
$array_name = array('function1', 'function2', 'function3');
foreach($array_name as $value) {
if($value()) {
// do stuff if the function returned a true-ish value
}
}
Another option to call the function would be call_user_func($value).
Try it:
$array_name = array('function1','function2','function3');
foreach($array_name as &$value) {
if(function_exists($value) && ($value())) {
//function exists and it returns true
}
}
Try to adopt things from : http://php.net/manual/en/functions.variable-functions.php
foreach($functionName as $arg) {
$arg();
}
But as you question contains:
$array_name = array(function1(),function2(),function3());
Make sure "function1()" is used in your array. So we can have:
foreach($functionName as $arg) {
$check = $arg;
if($check != false){
//Do stuff here
}else{
//Do stuff here
}
}
I would like to loop through the contents of a query object update certain values and return the object.
function clearAllIds($queryObject)
{
foreach($queryObject->result() as $row)
{
$row->id = 0;
}
return $queryObject
}
In this example I would like to zero out all of the ID values. How can I accomplish this within the foreach loop?
Please excuse the formatting.
This entirely depends on what the class of your query object is, and whether or not you'll be able to Pass by reference.
Assuming your $queryObject->result() can be delivered in a write-context, you could preface the $row with an ampersand to pass it by reference, like so:
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
function clearAllIds($queryObject)
{
foreach($queryObject->result() as &$row)
{
$row->id = 0;
}
return $queryObject
}
Use the & operator to get $row as a reference.
Edit: This will work if $queryObject is an array. You should probably do
$data = $queryObject->result();
foreach($data as &$row) { ... }
return $data;
function trim_spaces($object)
{
foreach (get_object_vars($object) as $property=> $value)
{
$object->$property=trim($value);
}
}
//no need to return object as they are passed by reference by default
I'm using PHP's global declaration to make an array available to a number of functions in a script. The variable is declared at the top of the script and is referenced with global in each of the functions which uses it, as follows:
<?php
$myarray = array(1, 2, 3);
function print_my_array() {
global $myarray;
print '<ul>';
foreach($myarray as $entry) {
print '<li>'.$entry.'</li>';
}
print '</ul>';
return 0;
}
print_my_array();
?>
Sometimes, but not always, the array is not set when the function is called, generating an error when the foreach is called. In the actual code, the array used is given a very unique name and so should not be causing any collisions with anything else. Am I mis-using the global declaration?
No, the snippet is correct. The problem you're having is the problem of using global variables – they can be accessed and changed from anywhere (perhaps accidental), thereby creating hard-to-find bugs.
By using globals you can hit quite a few gotchas, they'll also make you code less reusable.
Here's an example of your function which can be re-used many times across the site.
(untested)
<?php
function arrayTags($items, $open = '<li>', $close = '</li>')
{
if (is_array($items) && count($items) != 0)
{
$output = null;
foreach ($items as $item) {
$output .= $open . $item . $close;
}
return $output;
}
else
{
return '';
}
}
// Default, <li>
echo '<ul>' . arrayTags($myarray) . '</ul>';
// or, spans:
echo '<div id="container">' . arrayTags($myarray, '<span>', '</span>') . '</div>';
The least you could do is check if the array is null at the top of the function, before you run the foreach. that would at least prevent the error:
function print_my_array() {
global $myarray;
if(!empty($myarray)) {
print '<ul>';
foreach($myarray as $entry) {
print '<li>'.$entry.'</li>';
}
print '</ul>';
}
}
Also, I wouldn't just return 0 for the hell of it. You may want to incorporate whether or not the array was empty into what you return from this function.
$myarray = array(1, 2, 3);
In short you have to only declare it like so:
$myarray = array();
and if you want to populate it with values do that in the class constructor:
public function __construct(){
$myarray = array(1,2,3);
}
I'm no guru, but in my experience it seems that php doesn't like to execute function calls outside of a function within a class.
THIS DOES NOT WORK:
class MyClass {
public $mystring = myfunction();
public function myFunction(){
return true; //and your function code
}
}
so when you use array() it doesn't actually trigger any function call, it just creats an empty variable of type array. when you use array(1,2,3), it has to effectively run the 'create array' which is like a function.
I know annoying, I'd like it to be different, but I don't know a way of doing what you want in php. Let me know if there is a nice way I'd love to hear it!