Loop through Object in PHP - php

I am trying to read each element of an Object array, the code reads values from an excel file and then assign the values to a variable.
for ($row = 1; $row <= $highestRow; ++ $row) {
$fname = $worksheet->getCellByColumnAndRow(0, $row);
echo '<td>' . $fname . '<br></td>';
}
The output of 'fname' is four different names, however I want to read each value using a loop and then assign them to a link as follows:
www.example.com/fname so that four different links get opened up when I execute the code. I just can't figure out how to access each element of 'fname' object one by one. I read over examples available online, but to no avail. Please bear in mind I am a newbie to PHP. Thanks

Check if this works,
foreach($fname as $values)
{
$value1 = $values->keyname1;
$value2 = $values->keyname2;
$value3 = $values->keyname3;
$value4 = $values->keyname4;
}
$url = "http://example.com/".$value1;

If $fname contains a space delimited list of names like Tim John Sam Tom then you can use explode() to turn that STRING into an array of strings.
for ($row = 1; $row <= $highestRow; ++ $row) {
$fname = $worksheet->getCellByColumnAndRow(0, $row);
$names = explode(' ', $fname);
foreach ( $names as $name ) {
echo '<td>' . $name . '</td>';
}
}
So if you use the $names array
$names[0] would be `Tim`
$names[1] would be `John`
$names[2] would be `Sam`
$names[3] would be `Tom`

Related

MySQL mysqli_fetch_assoc field name & value. How?

The following code returns the field names of a result set. I also want it to return the values. How can I do this?
while ($row = mysqli_fetch_assoc($result)) {
foreach( $row as $field => $name) {
echo $field."<br>";
}
}
If we assume that your array looks like this:
$row["first_name"] = "John";
$row["last_name"] = "Doe";
$row["username"] = "john.doe";
Using this code:
while ($row = mysqli_fetch_assoc($result)) {
foreach( $row as $field => $value) {
echo "{$field} - {$value}<br>";
}
}
You will get an output like this:
first_name - John
last_name - Doe
username - john.doe
When you iterate through an array, using => operator, you are iterating in a "key-value" pair style. Every iteration holds the key and value as you can see.
Take a look at foreach for more information.
you are getting the value in $name variable
foreach( $row as $field => $name) {
echo $field . " = " . $name . "<br>";
}

Foreach is showing "Array" instead of selected items from dynamically generated checkboxes

I'm trying to capture a user's checkbox selection from a dynamically generated list of options but I'm getting "Array" instead of the names selected.
In my last test, I checked 2 of the three boxes and got 3 instances of "Array" back.
This is my query that finds the names:
$query = "SELECT id, first_name, last_name
FROM users WHERE location_id = " . $location_id;
$result = mysqli_query($connection, $query);
if (!$result)
{
die("Database query failed: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_array($result))
{
$name = $row['first_name'] . " " . $row['last_name'];
echo '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label>';
}
I then post the array of names like this:
$attendee = $_POST['emp_name'];
And try to generate the list of names for my email like this:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
Can someone help me see what's wrong?
I changed my code and included a part of the html that I'm trying to render:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
But it still returns Array.
Not sure why you do this:
$attendee = (array)$_POST['emp_name'];
Try to replace it with:
$attendee = $_POST['emp_name'];
From your question it's not too clear, but I think you're creating an array within an array,and that that's the issue.
If the above doesn't help, try to var_dump() the variable that gives you "Array" response, and you'll see what's within it.
EDIT: In addition to the change above, try to make this change too:
Replace all this code:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
with:
foreach ($_POST['emp_name'] as $name) {
$attendees[] = $name;
}
EDIT #2:
According to your code:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
It's totally normal that you're getting Array instead of a name. See, by writing:
$attendees[] = $name;
you're implying to php that it's an array. On the other hand the foreach loop does the opposite thing, it takes each of the values from $attendee array and makes it available to you as $name variable. So you're basically doing the right thing, and then reverting it back to array for no reason.
SOLUTION:
Replace {$attendees} with {$name}. And it should work.
You can write that with alot less code.
$attendees will now contain your checked checkboxes.
$attendees = array()
foreach($_POST['emp_name'] as $name){
$attendees[] = $name;
}

How to implode array that uses array_push in foreach loop

My tags are showing in the inner foreach loop in the right order.
I would like to comma separate them but am not sure how.
Is there a better way to display my tags without using the second foreach loop?
$people = array();
while($row = mysqli_fetch_array($rs, MYSQLI_ASSOC)){
if(!isset($people[$row["id"]])){
$people[$row["id"]]["id"] = $row["id"];
$people[$row["id"]]["tag"] = $row["tag"];
$people[$row["id"]]["tags"] = array();
}
array_push($people[$row["id"]]["tags"], array("id"=>$row["tags_id"],"tag_name"=>$row["tag"]));
}
foreach($people as $pid=>$p){
echo "(#{$p['id']}) ";
foreach($p["tags"] as $tid=>$t){
echo "<a href='#'>{$t['tag_name']}</a> ";
}
echo "<br><br>";
}
You don't need to use array_push, since you're only adding one element to the array. You can save the overhead of calling a function by using the syntax:
$people[ $row["id"] ]["tags"][] = array(...);
My answer depends on the necessity of the variables saved from the database. In your supplied code, you're only using the id and tag values from the database in the nested foreach loops. If this is this case, then you can simplify your arrays so you can use implode() on a new tags array. I have not tested this since I do not have your database schema, but I believe it will work.
<?php
$people = array();
$tags = array();
while( ($row = mysqli_fetch_array( $rs, MYSQLI_ASSOC)))
{
if( !isset( $people[$row['id']]))
{
$people[ $row['id'] ] = array( 'id' => $row['id'], 'tag' => $row['tag']);
$tags[ $row['id'] ] = array();
}
$tags[ $row['id'] ][] = $row['tag'];
}
foreach( $people as $pid => $p)
{
echo "(#{$p['id']}) ";
echo '' . implode( '', $tags[ $p['id'] ]) . '';
echo '<br /><br />';
}

How to fetch if a new query has been added

while($fetchres = mysql_fetch_array($searchquery)) {
$v1 = $fetchres['v1']; $v2 = $fetchres['v2']; $v3 = $fetchres['v3'];
$v4 = $fetchres['v4']; $v5 = $fetchres['v5'];
$v6 = $fetchres['v6'];
$v7 = $fetchres['v7'];
}
Hi! How can I set this columns automatically? I mean my system automatically adds a column. For example my system adds a new column 'v8'. But in my code, I only inputted until v7. How can I automatically code this fetching of query by depending on how many columns my system automatically made? Thanks.
Use extract.
while ($row = mysql_fetch_assoc($searchQuery))
{
// Extract the keys of the array into the local symbol table.
extract($row);
// Now, all variables exist and you can echo them like this:
echo $v1;
echo $v8;
}
You still need to know the names of the variables. If you just want to echo everything inside, use foreach with a key assingnment:
while ($row = mysql_fetch_assoc($searchQuery))
{
foreach($row as $key => $value)
{
echo "$key: $value\n"; // Will output something like 'v1: foo' and 'v2: bar', separated by newlines.
}
}
If you really want to do this, you can use extract($fetchres).
More info about extract
Example:
$fetchres = array('v1'=>'foo', 'v2'=>'bar');
extract($fetchres);
echo '$v1 is ' . $v1 . 'and $v2 is ' . $v2;
You could use variable variables for that, although I think this is a really bad idea.
I think you actually want this:
while ($fetchres = mysql_fetch_array($searchquery)) {
foreach ($fetchres as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}

php string name as variable in array

how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/

Categories