While loop in foreach loop not looping correctly - php

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
}

Related

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

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.

Codeigniter Active Record bug?

I just don't understand, I have code like this:
$this->ci->db->select('liked_posts, liked_comments');
$q = $this->ci->db->get_where('users_fav', array('usr_id' => $this->_usrId));
$result = $q->result_array();
And when I, as always, tried to put it into foreach loop.. it's just didn't work.. Because in $result I've got and array where 2 more arrays where stored (table fields)
so to work in foreach loop it would look like this:
foreach($result[0] as $value)
not:
foreach($result as $value)
And I was looking for my mistake very long.. Maybe I really did something wrong... Or is it a bug?
edit:
print_r($result);
Array
(
[0] => Array
(
[liked_posts] => a:0:{}
[liked_comments] => a:0:{}
)
)
edit2:
But shoudn't it be like this:
Array
(
[liked_posts] => a:0:{}
[liked_comments] => a:0:{}
)
?? Or I'm starting to go crazy???
edit3:
My bad... I realized now... I'm just going crazy.. too much work done today... better go sleep :D Sorry guys
so you can do this
foreach($result as $value)
{
echo $value['fav_posts'];
}
no problem with that.
When using $result = $q->result_array(); you will get a multidimentional array as you have now.:
foreach( $resuls as $key => $each ){
echo "result : ".$each['column_name'];
}
but if you have just a single row fetched you would likely use $result = $q->row_array(); which will return a single dimentional array. And you can directly use like this:
echo $results['column_name'];

getting information out of an array with key/value pairs

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'

How to search array for duplicates using a single array?

I am checking a list of 10 spots, each spot w/ 3 top users to see if a user is in an array before echoing and storing.
foreach($top_10['top_10'] as $top10) //loop each spot
{
$getuser = ltrim($top10['url'], " users/" ); //strip url
if ($usercount < 3) {
if ((array_search($getuser, $array) !== true)) {
echo $getuser;
$array[$c++] = $getuser;
}
else {
echo "duplicate <br /><br />";
}
}
}
The problem I am having is that for every loop, it creates a multi-dimensional array for some reason which only allows array_search to search the current array and not all combined. I am wanting to store everything in the same $array. This is what I see after a print_r($array)
Array ( [0] => 120728 [1] => 205247 ) Array ( [0] => 232123 [1] => 091928 )
There seems to be more to this code. As there are variables being called in it that aren't defined, such as $c, $usercount, etc.. And using array_search with the 2nd parameter of $array if it doesn't exist is not a good idea also. Since it seems like $array is being set within the if statement for this only.
And you don't seem to be using the $top10 value within the foreach loop at all..., why is this?
It would help to see more of the code for me to be able to help you.

Categories