In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).
Related
I have an array of names that I'd like to convert to variables. These are names of tests generated from a database (so if a new test is added a new index would be added to the array), our tests are updated on a regular basis so I don't want to hard-code my variables, I want to generate them dynamically.
I've tried this code:
$data = array();
foreach($tests as $v) {
$$v = ${};
array_push($data, $v);
}
My aim is to create the variables dynamically and then add to them for each instance of a test being taken, for example, if 6 people have had one of our instant tests, the variable 'instant' will have the value 6. Am I on the right track? Thanks!
***** UPDATE *****
Im trying to populate a morris.js chart using these variables, everything works when hard coded like so:
$pos = 0;
$neg = 0;
$pen = 0;
$cont = 0;
$misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
This gives me:
But im tryng to populate it dynamically from our databases so that if a new test / result set is added I don't have to go in and manually update the code, This is giving me data but no values as im not sure how to dynamically create variables based on the data:
/* Create dynamic variables: */
$vars = array();
foreach($tests as $k => $v) {
array_push($vars, $v);
$$v = extract($vars);
/* Loop through each instance and create a count for all matching instances */
foreach($data as $item){
if($item['name'] === $k){
${$v}++;
}
}
}
Is giving me the labels but with no value:
{"Positive","Negative","Pending","Contact the Clinic","Misc"}
Im currently using the Codeigniter (latest release) Cheers
Well if you use mysqli, you could do it like this:
// your query stuff:
$stmt->query($query);
$data = $stmt->fetch_assoc();
// just for example data contains:
// array('id'=>1,'name'=>'Andy')
foreach($data as $field => $value) {
${$field} = $value;
}
// then output:
echo $name; // should output 'Andy';
What about double dollar ?
You can read it here
http://php.net/manual/en/language.variables.variable.php
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 */
}
Alright I'm working with a large multidimensional array which has more information in it than I need and I want to loop through it to filter the data which I'm interested in. Sadly this multidimensional array is produced dynamically and doesn't always contain the data I want, so I have to use logic like:
if(isset($ar['b']['ba']['baa'])){
echo '<h3>'.$ar['b']['ba']['baa'].'</h3>';
}
if(isset($ar['b']['ba']['baba'])){
echo '<h3>'.$ar['b']['ba']['baba'].'</h3>';
}
if(isset($ar['b']['ba']['babb'])){
echo '<h3>'.$ar['b']['ba']['babb'].'</h3>';
}
The above works great but its a bit messy-looking so I converted the above to:
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
The above looks a lot more nice and neat and is how I want to control the script in case I need to reference different keys in the future. The problem I am having is trying to use the above format to actually reference the array. I thought variable variables would work but apparently it fails. My second attempt using eval worked but I'm not very happy with my solution. This is where I need you guys to come in, is there a better way to do this? Here's my attempt below:
<?php
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
$refAr=array();
$refAr[]='b->ba->baa';//3
$refAr[]='b->ba->bab->baba';//4
$refAr[]='b->ba->bab->babb';//5
foreach($refAr as $ref)
{
$r=explode('->',$ref);
$r="\$ar['".implode("']['",$r)."']";
echo '<h1>'.$r.'</h1>';
echo '<h3>'.$$r.'</h3>';//undefined
eval('$t='.$r.';');
echo "<h3>$t</h3>";//works but uses eval, is there a better way?
}
You can try
$ar = array();
$ar['b']['ba']['baa'] = 3;
$ar['b']['ba']['bab']['baba'] = 4;
$ar['b']['ba']['bab']['babb'] = 5;
$refAr = array();
$refAr[] = 'b->ba->baa'; // 3
$refAr[] = 'b->ba->bab->baba'; // 4
$refAr[] = 'b->ba->bab->babb'; // 5
foreach ( $refAr as $ref ) {
$t = $ar;
foreach ( explode("->", $ref) as $v ) {
if (!isset($t[$v]))
break;
$t = $t[$v];
}
is_array($t) and $t = null;
echo "<h3>$t</h3>";
}
Output
345
I decided to answer my own question. This is what I wound up using:
<?php
//Sample PHP representation of dynamically-pulled JSON data from an untrusted source
$ar=array(
'a'=>array('aa'=>1,'ab'=>2),
'b'=>array(
'ba'=>array('baa'=>3,'bab'=>array('baba'=>4,'babb'=>5),'bac'=>array('baca'=>6,'bacb'=>7)),
)
);
//Reusable function
function resolveReference($ar,&$ref)
{
$t = $ar;
foreach ( explode('->',$ref) as $v )
{
if (!array_key_exists($v,$t)){$ref=null;return false;}
$t = $t[$v];
}
$ref=$t;
return true;
}
//The references I'm interested in but don't know if my dynamic data will contain these keys every time
$refAr=array();
$refAr[]='b->ba->baa';
$refAr[]='b->ba->bab->baba';
$refAr[]='b->ba->bab->babb';
$refAr[]='b->doesnt->exist';
foreach($refAr as $ref)
{
echo '<h1>'.$ref.'</h1>';
if(resolveReference($ar,$ref))
{
echo '<h3><span style="color:blue;">'.$ref.'</span></h3>';
}else{
echo '<h3><span style="color:red;">Alternative text for non-existent expected reference</span></h3>';
}
}
Hi I have a PHP array with a variable number of keys (keys are 0,1,2,3,4.. etc)
I want to process the first value differently, and then the rest of the values the same.
What's the best way to do this?
$first = array_shift($array);
// do something with $first
foreach ($array as $key => $value) {
// do something with $key and $value
}
I would do this:
$firstDone = FALSE;
foreach ($array as $value) {
if (!$firstDone) {
// Process first value here
$firstDone = TRUE;
} else {
// Process other values here
}
}
...but whether that is the best way is debatable. I would use foreach over any other method, because then it does not matter what the keys are.
Here is one way:
$first = true;
foreach($array as $key => $value) {
if ($first) {
// something different
$first = false;
}
else {
// regular logic
}
}
$i = 0;
foreach($ur_array as $key => $val) {
if($i == 0) {
//first index
}
else {
//do something else
}
$i++;
}
I would do it like this if you're sure the array contains at least one entry:
processFirst($myArray[0]);
for ($i=1; $i<count($myArray); $1++)
{
processRest($myArray[$i]);
}
Otherwise you'll need to test this before processing the first element
I've made you a function!
function arrayCallback(&$array) {
$callbacks = func_get_args(); // get all arguments
array_shift($callbacks); // remove first element, we only want the callbacks
$callbackindex = 0;
foreach($array as $value) {
// call callback
$callbacks[$callbackindex]($value);
// make sure it keeps using last callback in case the array is bigger than the amount of callbacks
if(count($callbacks) > $callbackindex + 1) {
$callbackindex++;
}
}
}
If you call this function, it accepts an array and infinite callback arguments. When the array is bigger than the amount of supplied functions, it stays at the last function.
You can simply call it like this:
arrayCallback($array, function($value) {
print 'callback one: ' . $value;
}, function($value) {
print 'callback two: ' . $value;
});
EDIT
If you wish to avoid using a function like this, feel free to pick any of the other correct answers. It's just what you prefer really. If you're repeatedly are planning to loop through one or multiple arrays with different callbacks I suggest to use a function to re-use code. (I'm an optimisation freak)
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