I have a query which converts item rows of a series of IDs in MySQL table to columns, so the result has variable number of columns (VC). The only items that are not dynamic are the ID, FirstName, LastName. I know the number of variable items (n), which is part of the query.
what I want to do is to have a loop inside PHP while to add these variable columns to the PHP array.
something like this:
$someArray = [];
while($row = $result -> fetch_assoc()) {
array_push($someArray,[
'ID' => $row['EmployeeID'],
'FName' => $row['FName'],
'MName' => $row['MName'],
'LName' => $row['LName'],
-------Loop here --------
'VC1' => $row['VC1'],
'VC2' => $row['VC2'],
'VC3' => $row['VC3'],
'VC4' => $row['VC4'],
'VC5' => $row['VC5'],
..............
'VCn' => $row['VCn']
-------------------------
]);
}
I tried with PHP loop and could not figure out how to do it.
Thanks for any help in advance.
If you know n you can use for loop:
for($i = 1;$i <= $n; $i++) {
$key = "VC" .$i;
$someArray[$key] = $row[$key];
}
However, if you pushing the entire array in it may be better do modify your SQL query and do just:
while($row = $result -> fetch_assoc())
array_push($someArray, $row)
Related
New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.
You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.
new to php, I have read dozens of 'insert data into arrays' posts on the net, but none seem to describe my exact problem, (or I am too ignorant to recognize it) So here we go.
I get some data from a SQL database. I want to present this in a table. I have a working script that does this, but it has a slight malfunction, it doesn't show any empty results (rows) in the table. To get the desired result I my attempt 2.0 starts now with an empty table, with all the rows, and fill them in with data later.
$names = array('Alice', 'Bob', 'Charles', 'Dick', 'Emy');
for ($i=0; $i< count($names); $i++)
{
$empty_table[] = array("Name" => $names[$i], "Total" => 0, "Wins" => 0, "Losses" => 0) ;
}
This gives me an array that I can display as a table, with 5 data rows, each containing a value for the field with a Name key (Alice to Emy) and otherwise filled with values set to 0 for all other keys. It looks like:
Name Total Wins Losses
Alice 0 0 0
Bob 0 0 0
Charles 0 0 0
Dick 0 0 0
Emy 0 0 0
From the database I want to fill in the values that are 0, IF and only IF there is something in the database. I get the data with
for ($i=0; $i< count($names); $i++) {
$sql = "SELECT
SEVERAL THINGS
WHERE Something = '".$names[$i]."'";
$result = mysqli_query($conn,$sql);
// Not the real query obviously, but that part works and gives the intended result.
while ( $row = mysqli_fetch_assoc($result) ) {
Do something with the result in $row;
} // end while
} // end for
$row is an array with the same structure as one of the values of $empty_table. Example:$row could be: Array ( [Name] => Bob [Total] => 10 [Wins] => 7 [Losses] => 3 )
Now the question. How do I get the one dimension array $row into the two dimension array $empty_table (replacing the '0' values) , given that $empty_table always has a fixed 5 elements but there can be any number between 0 and 5 '$row's in the while loop depending on what is in the database?
If I try:
$empty_table[] = $row;
or
$empty_table[$row['Name']] = $row;
I only get rows added to the existing array with '0' values, not rows replaced. I do understand that the solution is between the '[]' but I can't figure out put something there that relates to the proper $row[].
I think that you can change the array construction to this:
for ($i=0; $i< count($names); $i++) {
$empty_table[$names[$i]] = array("Name" => $names[$i], "Total" => 0, "Wins" => 0, "Losses" => 0) ;
}
So your array keys will be the name of the person. With this you can identify what row is each moment. The array should be constructed like this:
$empty_table = Array(
"John"=> Array("name"=>"John", "total"=>10, "wins"=>3, "loses"=>7),
"Mary"=> Array("name"=>"Mary", "total"=>10, "wins"=>5, "loses"=>5),
);
So you can access to the values like this:
$john_row = $empty_table["John"];
I am just pretending that the $row is from db.
<?php
$names = array('Alice', 'Bob', 'Charles', 'Dick', 'Emy');
for ($i=0; $i< count($names); $i++)
{
$empty_table[] = array("Name" => $names[$i], "Total" => 0, "Wins" => 0, "Losses" => 0) ;
}
$row = array("Name" => 'Alice', "Total" => 5, "Wins" => 6, "Losses" => 4);
$found = false;
foreach($empty_table as $k=>$a) {
if($a['Name'] == $row['Name']) {
$found = true;
break;
}
}
if($found) {
echo 'index found'.$k.'\n';
$empty_table[$k] = array_replace($empty_table[$k], $row);
var_dump($empty_table);
}
I have a query that populates an array from the database. In some cases, this query returns a great amount of data, (let's say for purpose of an example, 100.000 records). Each row of the database has at least 6 or 7 columns.
$results = [
['id' => 1, 'name' => 'name', 'status' => true, 'date' => '10-01-2012'],
['id' => 2, 'name' => 'name 2', 'status' => false 'date' => '10-01-2013'],
...
]
I need to perform a substitution of some of the data inside the $results array, based on another one that give me some information about how i would change the values in the rows.
$model = [
'status' => ['function' => 'formatStatus', params => ['status']],
'date' => ['function' => 'formatDate', params => ['date']]
]
Now that i have all the data and what do i do with it i have the following routine.
foreach ($results as &$itemResult) {
$oldValues = $itemResult;
foreach ($itemResult as $attribute => &$value) {
if (isset($model[$attribute]['function'])) {
$function = $model[$attribute]['function'];
$params = $model[$attribute]['params'];
$paramsSize = count($params);
for ($i = 0; $i < $paramsSize; $i++) {
$newParams[] = $oldValues[$params[$i]];
}
$itemResult[$attribute] = call_user_func_array([$this, $function], $newParams);
$newParams = null;
}
}
}
So, for each attribute for each row of my data array, i run check for the existence of a function and params information. When the attribute in question needs to be replaced, i call the function via call_user_func_array and replace the value with the function return value.
Also notice that i am replacing the current array, not creating another, by passing the reference &$itemResult inside the loop, so in the end, i have the same array from the beginning but with all columns that needed to be replaced with its new values.
The thing is, for little arrays, this method is quite good. But for big ones, it becomes a pain.
Could you guys provide me some alternative to the problem?
Should i use another data structure instead of the PHP array?
What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.
Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push
i need help building a function that display an associative array and i want to insert them in a variable. for example i have this assoc array :
$array[ID] = 1;
$array[Name] = John;
$array[age] = 12;
$array[ID]=2;
$array[Name] = Mary;
$array[age] = 14;
i need to make the ID,name,age as variables so i can display it in a table. when i loop through them each time it fills the table row. it has to be each one a variable coz i need to insert them into a gird and display the grid .. where then i can update delete the info
I'd use one of the answers provided but if you really really want to (again, i don't see a reason but what the hell do i know) use extract()
<?php
$people = array(
array('id' => 1, 'name' => 'John', 'age' => 12),
array('id' => 2, 'name' => 'Mary', 'age' => 14)
);
foreach($people as $row) {
extract($row);
echo "Id: $id, Name: $name, Age: $age\n";
}
//Prints:
//Id: 1, Name: John, Age: 12
//Id: 2, Name: Mary, Age: 14
~
Currently it looks as if you are overwriting the values of the first person with the values of the second person.
What you're looking for is an array structure with more than one dimension, like this:
$people = array(
1 => array('name' => 'John', 'age' => 12),
2 => array('name' => 'Mary', 'age' => 14)
);
Then it'll be easy to print out table rows:
foreach($people as $id => $person){
print '<tr><td>'.$id.'</td><td>'.$person['name'].'</td><td>'.$person['age'].'</td></tr>';
}//foreach
Hope this helps!
foreach($array as $row) {
echo $row['ID'],$row['Name'],$row['age'];
}
Im not sure what you want to do exactly, but maybe it is the extract function you are looking for.
foreach($array as $key => $value){
echo $key. ' = '.$value.";
}
would give you
ID = 1
Name = John
age = 12
etc
Also be sure to do $array["ID"] = ... instead of $array[ID] = ...
You can do:
foreach($array as $user) {
list($age, $name, $id) = array_values($user);
echo $id, $name, $age;
}
But like others already pointed out, this is pointless because you can much more easily read the values directly from the array through their associative keys. You also wouldnt have to run array_values to assign the array values before being able to assign them with list.