Passing an array of variables FROM an object - php

So here's what I want to do, I have a class and within SomeClass, there's a function consists of 2 variables, each has a numerical value. I want to return an array of the two variables which have dependencies in post data outside of SomeClass from a form that posts to itself.
<?php
class SomeClass{
private $someVar1;
private $someVar2;
public function setVars($var1,$var2) {
$this->someVar1 = $var1;
$this->someVar2 = $var2;
}
function __construct() {
}
function setFraction() {
$sum['num'] = 140*pow($this->someVar1,0.75);
$sum['den'] = $sum['num']/$this->someVar2;
return $sum;
}
}
if(isset($_POST['num'])){$num = preg_replace('/\D/', '', $_POST['num']);}
elseif(isset($_POST['den'])){$den = preg_replace('/\D/', '', $_POST['den']);}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Numerator:<input type="text" value="<?php if(isset($num)){echo $num;}?>" name="num" /><br />
Denominator:<input type="text" value="<?php if(isset($den)){echo $den;}?>" name="den" /><br />
<input type="submit" value="Go" name="Go">
</form>
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$sum=$obj->setFraction();?>
<pre>
<?php print_r($obj->setFraction());?>
</pre>
<ul>
<?php foreach($sum as $val):?>
<li><?php echo $val['num']?></li>
<li><?php echo $val['den']?></li>
<?php endforeach;?>
</ul>
<?php endif;?>
When I run the script, post data for $num and $den is being sent and returned with setFraction(), however when I try to iterate through the array in a foreach loop, I don't get any return data. I'm sure its something simple, I've tried it with a foreach loop and without with same results, any help would be excellent, thx.
EDIT:
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$array = $obj->setFraction();?>
<ul>
<li><?php echo $array['num']?></li>
<li><?php echo $array['den']?></li>
</ul>
<?php endif;?>

Store the returned data to some variable,and then iterate.
//
<?php if(isset($num,$den)):
$obj = new SomeClass();
$obj->setVars($num,$den);
$array = $obj->setFraction();?>
<ul>
<?php foreach($array as $val):?>
<li><?php echo $val['num']?></li>
<li><?php echo $val['den']?></li>
<?php endforeach;?>
</ul>
<?php endif;?>

you haven't assign $sum=$obj->setFraction(); to $sum

auYou're not assigning the return values of $obj->setFraction() to a variable. You need to do:
$sum=$obj->setFraction();
and all should be OK.
Just becuase you're returning a variable called $sum doesn't mean that that variable name is used once it's back in the main body of your script.
I have just noticed, as you rightly state in your acceptance, that you don't need the foreach block. Just use $sum['num'] and $sum['den']. Sorry about that - I should have noticed earlier

You should use $obj->sum instead of $sum.

Related

Fixing my search form in HTML with embedded PHP?

So I have a PHP page which has an ordered list that I am scanning from a text file which looks like this:
Here is the code for it as well:
<?php
foreach (file("Files/music.txt") as $music){
list($title,$artist,$link) = explode(",",$music);
?>
<li>
<a href=<?php echo $link ?>><?php echo $title ?> by <?php echo $artist ?></a>
</li>
<?php } ?>
</ol>
</div>
What I need is to be able to search the title for the song and to only display that with the form I have in the picture. I have to use only the $_GET and a function to make it work. Here is the code for the form that I am messing around with:
<form action="blog.php">
Search for Title:
<input type="text" name="title">
<input type="submit" value="Search">
<br>
Sort by song title
Unsorted
<?php
function printSongs($searchTitles=""){
if(isset($searchTitles)){
global $title;
if ($searchTitle == $title){
echo $title;
}
}
}
$userInput = $_GET["title"];
printSongs($userInput);
?>
</form>
Any advice would help alot. Thank you!
try using The SplFileObject class in PHP try this code
<?php
function printSongs($searchTitles=""){
$file = new SplFileObject("Files/music.txt");
$music="";
while (!$file->eof()) {
$music= $file->fgets();
$data= explode(",",$music);
if (in_array($searchTitles, $data))
{
//match is found
echo data[1];
}
}
}
$userInput = $_GET["title"];
printSongs($userInput);
?>

Print the specific values from the array

I get the result from my database i this type of array format.Now i want to print the question,answer and category name from the array what I do?
<?php $v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data->title;?>">
I tried these cod but not get the answer.In $var i get the all the array value
Things to consider:-
1.Your sub-array is again an array so you need to use foreach() on sub-array too. (So basically two foreach())
2.You need to close divs as well as foreach() loops too.
So code need to be like below:-
<?php
foreach($var as $data){
foreach($data['data'] as $dat){
?>
<div class="faqHeader"> <?php echo $dat['category_name'];?>
<div class="panel-group" id="<?php echo $dat['questions'];?>"><?php echo $dat['questions'];?></div>
<div class="panel-group" id="<?php echo $dat['answer'];?>"><?php echo $dat['answer'];?></div>
</div>
<?php } }?>
you can use two loops to simplify your task:-
foreach($var as $index=>data){
echo $data['name']; // this will be your category name
foreach($data as $questionIndex=>$questionData){
echo $questionData['question'];
echo $questionData['answer'];
}
}
Since your array contains multiple data and data contains multiple values itself, you need two foreaches here:
foreach($var as $item) {
foreach($item['data'] as $info) {
var_dump($info);
}
}
Please try this code
<?php
$v1 = '';
foreach($var as $data){
?>
<div class="faqHeader"> <?php echo $data['data'][0]['category_name'];?> </div>
<div class="panel-group" id="<?php echo $data['name'];?>">
<?php
}
?>
You don't have any 'title' index in your array so you may change it to 'name'

For each inside other for each on view MVC PHP

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>

PHP Error: Cannot use object of type stdClass as array (array and object issues) [duplicate]

This question already has answers here:
Cannot use object of type stdClass as array?
(17 answers)
Closed 9 years ago.
I was trying to copy this code:
<?php
foreach ($products as $product) {
$id = $product['id'];
$name = $product['name'];
$description = $product['description'];
$price = $product['price'];
?>
<tr>
<td><img src="<?php echo $product['picture']; ?>" /></td>
<td><b><?php echo $name; ?></b><br />
<?php echo $description; ?><br />
Price:<big style="color:green">
$<?php echo $price; ?></big><br /><br />
<?php
echo form_open('cart/add');
echo form_hidden('id', $id);
echo form_hidden('name', $name);
echo form_hidden('price', $price);
echo form_submit('action', 'Add to Cart');
echo form_close();
?>
</td>
</tr>
<tr><td colspan="2"><hr size="1" /></td>
<?php
}
?>
and here is my code:
<?php
foreach ($blogs as $blog) {
$id = $blog['id'];
$title = $blog['title'];
$content = $blog['content'];
?>
<h1><?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php
}
?>
I get this error every time I run my code: "Cannot use object of type stdClass as array"
The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.
If you don't know the variable names, just do a var_dump($blog); within the loop to see them.
The simplest method - access $blog as an object directly:
Try (assuming those variables are correct):
<?php
foreach ($blogs as $blog) {
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
The alternative method - access $blog as an array:
Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):
<?php
foreach($blogs as &$blog) {
$blog = get_object_vars($blog);
$id = $blog['id'];
$title = $blog['title'];
$content = $blog['content'];
?>
<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.
Better than either of the above - Inline PHP Syntax
Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:
<?php foreach($blogs as $blog): ?>
<h1><?php echo $blog->title; ?></h1>
<p><?php echo $blog->content; ?></p>
<?php endforeach; ?>
Hope this helped.
$blog is an object not an array
try using $blog->id instead of $blog['id']
$blog is an object, not an array, so you should access it like so:
$blog->id;
$blog->title;
$blog->content;
There might two issues
1) $blogs may be a stdObject
or
2) The properties of the array might be the stdObject
Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this
$blog->id;
$blog->content;
$blog->title;
If you're iterating over an object instead of an array, you'll need to access the properties using:
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
That, or change your object to an array.
StdClass object is accessed by using ->
foreach ($blogs as $blog) {
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
}

Is this an array with foreach?

I have three variables ($var, $var2 & $var3) and I want it to output when they have value.
For example, if $var = "Data"; then:
<ul>
<li>Data</li>
</ul>
And if any of the other variables has value then:
<ul>
<li>Data</li>
<li>Data2</li>
</ul>
Or
<ul>
<li>Data</li>
<li>Data3</li>
</ul>
<ul>
<li>Data</li>
<li>Data3</li>
<li>Data2</li>
</ul>
I am not exactly sure how to create this and with what method considering everybody has different ways of doing their php code. Does anybody know how I can create this?
Also: I use http://writecodeonline.com/php/ when testing certain php codes.
<ul>
<?php foreach (array($var1, $var2, $var3) as $var) : ?>
<?php if (!empty($var)) : ?>
<li><?php echo $var; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
You can see the output here on writecodeonline.com.
Or maybe you prefer this:
<ul>
<?php
foreach (array($var1, $var2, $var3) as $var) {
if (!empty($var)) {
echo '<li>' . $var . '</li>';
}
}
?>
</ul>
(it doesn't matter really, just use whatever you think looks better)
You can try:
<ul>
<?php foreach(array($var, $var2, $var3) as $value) : ?>
<?php if (!empty($value)) : ?>
<li><?php echo $value; ?></li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
I suppose from the title that your variables are inside an array.
If so, just do a foreach loop
foreach($arrayVars as $var)
{
if(isset($var))
{
echo '<li>'.$var.'</li>
}
}
Anyway, you should explain clearly what your problem is. I making assumptions here because your not very explicit on what your problem is.
Use an array, and foreach to print the variables.
http://php.net/manual/en/language.types.array.php
or you can use this (what I not recommend):
if(isset($var)) {
echo $var;
}
if(isset($var1)) {
echo $var1;
}
if(isset($var2)) {
echo $var2;
}
Best is var-args in my opinion.
function funcName() {
for ($i = 0;$i < func_num_args();$i++) {
echo '<li>'.func_get_arg($i).'</li>';
}
echo funcName($var,$var1,$var2);

Categories