getting information out of an array with key/value pairs - php

I have the following snippet of code that is creating the following array...
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Results in the follow array:
Array ( [0] => Array ( [cap_login] => master [cap_pword] => B-a411dc195b1f04e638565e5479b1880956011badb73361ca ) )
Basically I want to extract the cap_login and cap_pword values for testing. For some reason I can't get it!
I've tried this kind of thing:
echo $results[$cap_login];
but I get the error
Undefined variable: cap_login
Can someone put me right here?
Thanks.

cap_login is in an array within $results so you would have to do $results[0]['cap_login']

You would have to do the following:
echo $x[0]['cap_login'] . '<br />';
echo $x[0]['cap_pword'];
The reson $results[$cap_login] wont work is because there isn't a variable called $cap_login, there is a string called cap login. In addition, there isn't a key in $results called $cap_login. There is a value in $results called 'cap_login'

Related

return data using variable variables

$raw_data = array ('data' => array ('id' => 'foo'));
$fields = array ('id_source' => "data['id']");
foreach ($raw_data as $data) {
foreach ($fields as $key => $path) {
var_dump ($data['id']);
var_dump ($$path);
}
}
The first var_dump gives me the correct value of foo. However, the second one gives me Undefined variable: data['id']. Can anyone tell me why that would be the case, especially since the first var_dump worked confirming the variable $data['id'] is set.
I realized this example is basic and I could just do $data[$key] and change $fields = array ('id_source' => 'id'); but I want to be able to go deeper into the multidimensional arrays when needed. That is why I'm trying to do my original approach.

Copy array into another array in PHP

I am trying to copy array into another array in PHP. Then send the response as JSON output. But it copies only the last element in array multiple times. Please let me know where I am going wrong? Any help is appreciated
PHP code
stmt_bind_assoc($stmt, $resultrow);
while ($stmt->fetch()) {
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Output from print_r($resultrow).This is correct. Values in array is different
Array( [a_id] => 1 [b_number] => 10101010 [dateandtime] => 2013-12-25 09:30:00 )
Array( [a_id] => 1 [b_number] => 20202020 [dateandtime] => 2013-12-27 11:40:00 )
Output from json_encode($r).This is incorrect. Values in array is same
[{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"},
{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"}]
You got the function stmt_bind_assoc from here: http://www.php.net/manual/en/mysqli-stmt.fetch.php#82742
Posted under that OP is:
"...the problem is that the $row returned is reference and not data.
So, when you write $array[] = $row, the $array will be filled up with
the last element of the dataset."
With that user's solution I came up with this to resolve your issue:
// replace your posted code with the following
$r = array();
// loop through all result rows
while ( $stmt->fetch() ) {
$resultrow = array();
foreach( $row as $key=>$value )
$resultrow[ $key ] = $value;
$r[] = $resultrow;
print_r($resultrow);
}
echo json_encode($r);
Next time you get code from a source read the comments about the source.

key and value array access in php

I am calling a function like:
get(array('id_person' => $person, 'ot' => $ot ));
In function How can I access the key and value as they are variable?
function get($where=array()) {
echo where[0];
echo where[1];
}
How to extract 'id_person' => $person, 'ot' => $ot without using foreach as I know how many key-values pairs I have inside function?
You can access them via $where['id_person'] / $where['ot'] if you know that they will always have these keys.
If you want to access the first and second element, you can do it like this
reset($where)
$first = current($where);
$second = next($where);
Couple ways. If you know what keys to expect, you can directly address $where['id_person']; Or you can extract them as local variables:
function get($where=array()) {
extract($where);
echo $id_person;
}
If you don't know what to expect, just loop through them:
foreach($where AS $key => $value) {
echo "I found $key which is $value!";
}
Just do $where['id_person'] and $where['ot'] like you do in JavaScript.
If you do not care about keys and want to use array as ordered array you can shift it.
function get($where=array()) {
$value1 = array_shift($where);
$value2 = array_shift($where);
}

How to access mysql result set data with a foreach loop

I'm developing a php app that uses a database class to query MySQL.
The class is here: http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql/*note there are multiple bad practices demonstrated in the tutorial -- it should not be used as a modern guide!
I made some tweaks on the class to fit my needs, but there is a problem (maybe a stupid one).
When using select() it returns a multidimensional array that has rows with 3 associative columns (id, firstname, lastname):
Array
(
[0] => Array
(
[id] => 1
[firstname] => Firstname one
[lastname] => Lastname one
)
[1] => Array
(
[id] => 2
[firstname] => Firstname two
[lastname] => Lastname two
)
[2] => Array
(
[id] => 3
[firstname] => Firstname three
[lastname] => Lastname three
)
)
Now I want this array to be used as a mysql result (mysql_fetch_assoc()).
I know that it may be used with foreach(), but this is with simple/flat arrays. I think that I have to redeclare a new foreach() within each foreach(), but I think this could slow down or cause some higher server load.
So how to apply foreach() with this multidimensional array the simplest way?
You can use foreach here just fine.
foreach ($rows as $row) {
echo $row['id'];
echo $row['firstname'];
echo $row['lastname'];
}
I think you are used to accessing the data with numerical indices (such as $row[0]), but this is not necessary. We can use associative arrays to get the data we're after.
You can use array_walk_recursive:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
With arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
This would have been a comment under Brad's answer, but I don't have a high enough reputation.
Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.
In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows
foreach ($mda as $mdaKey => $mdaData) {
echo $mdaKey . ": " . $mdaData["value"];
}
Hope that helps someone.
Holla/Hello,
I got it! You can easily get the file name,tmp_name,file_size etc.So I will show you how to get file name with a line of code.
for ($i = 0 ; $i < count($files['name']); $i++) {
echo $files['name'][$i].'<br/>';
}
It is tested on my PC.
To get detail out of each value in a multidimensional array is quite straightforward once you have your array in place. So this is the array:
$example_array = array(
array('1','John','Smith'),
array('2','Dave','Jones'),
array('3','Bob','Williams')
);
Then use a foreach loop and have the array ran through like this:
foreach ($example_array as $value) {
echo $value[0]; //this will echo 1 on first cycle, 2 on second etc....
echo $value[1]; //this will echo John on first cycle, Dave on second etc....
echo $value[2]; //this will echo Smith on first cycle, Jones on second etc....
}
You can echo whatever you like around it to, so to echo into a table:
echo "<table>"
foreach ($example_array as $value) {
echo "<tr><td>" . $value[0] . "</td>";
echo "<td>" . $value[1] . "</td>";
echo "<td>" . $value[2] . "</td></tr>";
}
echo "</table>";
Should give you a table like this:
|1|John|Smith |
|2|Dave|Jones |
|3|Bob |Williams|
Example with mysql_fetch_assoc():
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach, with the $result array you get from select():
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
Ideally a multidimensional array is usually an array of arrays so i figured declare an empty array, then create key and value pairs from the db result in a separate array, finally push each array created on iteration into the outer array. you can return the outer array in case this is a separate function call. Hope that helps
$response = array();
foreach ($res as $result) {
$elements = array("firstname" => $result[0], "subject_name" => $result[1]);
array_push($response, $elements);
}
I know this is quite an old answer.
Here is a faster solution without using foreach:
Use array_column
print_r(array_column($array, 'firstname')); #returns the value associated with that key 'firstname'
Also you can check before executing the above operation
if(array_key_exists('firstname', $array)){
print_r(array_column($array, 'firstname'));
}
Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?
when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.
That should be the same as mysql_fetch_assoc would give (in a loop) for each row.
foreach ($parsed as $key=> $poke)
{
$insert = mysql_query("insert into soal
(pertanyaan, a, b, c, d, e, jawaban)
values
('$poke[question]',
'$poke[options][A]',
'$poke[options][B]',
'$poke[options][C]',
'$poke[options][D]',
'$poke[options][E]',
'$poke[answer]')");
}
If you need to do string manipulation on array elements, e.g, then using callback function array_walk_recursive (or even array_walk) works well. Both come in handy when dynamically writing SQL statements.
In this usage, I have this array with each element needing an appended comma and newline.
$some_array = [];
data in $some_array
0: "Some string in an array"
1: "Another string in an array"
Per php.net
If callback needs to be working with the actual values of the array,
specify the first parameter of callback as a reference. Then, any
changes made to those elements will be made in the original array
itself.
array_walk_recursive($some_array, function (&$value, $key) {
$value .= ",\n";
});
Result:
"Some string in an array,\n"
"Another string in an array,\n"
Here's the same concept using array_walk to prepend the database table name to the field.
$fields = [];
data in $fields:
0: "FirstName"
1: "LastName"
$tbl = "Employees"
array_walk($fields, 'prefixOnArray', $tbl.".");
function prefixOnArray(&$value, $key, $prefix) {
$value = $prefix.$value;
}
Result:
"Employees.FirstName"
"Employees.LastName"
I would be curious to know if performance is at issue over foreach, but for an array with a handful of elements, IMHO, it's hardly worth considering.
A mysql result set object is immediately iterable within a foreach(). This means that it is not necessary to call any kind of fetch*() function/method to access the row data in php. You can simply pass the result set object as the input value of the foreach().
Also, from PHP7.1, "array destructuring" allows you to create individual values (if desirable) within the foreach() declaration.
Non-exhaustive list of examples that all produce the same output: (PHPize Sandbox)
foreach ($mysqli->query("SELECT id, firstname, lastname FROM your_table") as $row) {
vprintf('%d: %s %s', $row);
}
foreach ($mysqli->query("SELECT * FROM your_table") as ['id' => $id, 'firstname' => $firstName, 'lastname' => $lastName]) {
printf('%d: %s %s', $id, $firstName, $lastName);
}
*note that you do not need to list all columns while destructuring -- only what you intend to access
$result = $mysqli->query("SELECT * FROM your_table");
foreach ($result as $row) {
echo "$row['id']: $row['firstname'] $row['lastname']";
}

While loop in foreach loop not looping correctly

I'm trying to make a very basic php ORM as for a school project. I have got almost everything working, but I'm trying to map results to an array. Here's a snippet of code to hopefully assist my explanation.
$results = array();
foreach($this->columns as $column){
$current = array();
while($row = mysql_fetch_array($this->results)){
$current[] = $row[$column];
print_r($current);
echo '<br><br>';
}
$results[$column] = $current;
}
print_r($results);
return mysql_fetch_array($this->results);
This works, but the while loop only works on the first column. The print_r($results); shows the following:
Array ( [testID] => Array ( [0] => 1 [1] => 2 ) [testName] => Array ( ) [testData] => Array ( ) )
Can anybody shed some light?
Thanks in advance!
It's because you already fetched every row, and the internal pointer is at the end.
The next while, mysql_fetch_array() will immediately return false.
You can reset the pointer to the first row:
mysql_data_seek($this->results, 0);
Put this just before
while($row = mysql_...
I'm not sure you can use the -> operator in a variable name. As you trying to get the key and value out of the array $columns? If so, you want something like this:
foreach($columns as $k => $v) {
//in here, $k is the name of the field, and $v is the associated value
}

Categories