Copy array into another array in PHP - 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.

Related

How to make key value by explode and arrange matching key values into one key?

I am recently facing a practical problem.I am working with ajax form submission and there has been some checkboxes.I need all checkboxes with same name as key value pair.Suppose there is 4 checkboxes having name attribute =checks so i want something like $arr['checks'] = array(value1, value2, ...)
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
I am using below code to make into an array
public function smdv_process_option_data(){
$dataarray = array();
$newdataarray = array();
$new = array();
$notices = array();
$data = $_POST['options']; // data received by ajax
$dataarray = explode('&', $data);
foreach ($dataarray as $key => $value) {
$i = explode('=', $value);
$j = 1;
if(array_key_exists($i[0], $newdataarray)){
if( !is_array($newdataarray[$i[0]]) ){
array_push($new, $newdataarray[$i[0]]);
}else{
array_push($new, $i[1]);
}
$newdataarray[$i[0]] = $new;
}else{
$newdataarray[$i[0]] = $i[1];
}
}
die($newdataarray);
}
Here i want $newdataarray as like below
array(
'name' => 'alex',
'checks => array(code1, code2, code3),
)
But any how I am missing 2nd value from checks key array.
As I see it you only need to do two explode syntaxes.
The first on is to get the name and here I explode on & and then on name= in order to isolate the name in the string.
The checks is an explode of &checks= if you omit the first item with array_slice.
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$name = explode("name=", explode("&", $str)[0])[1];
// alex
$checks = array_slice(explode("&checks=", $str), 1);
// ["code1","code2","code3"]
https://3v4l.org/TefuG
So i am getting my ajax $_POST code as suppose like: name=alex&checks=code1&checks=code2&checks=code3
Use parse_str instead.
https://php.net/manual/en/function.parse-str.php
parse_str ( string $encoded_string [, array &$result ] ) : void
Parses encoded_string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).
$s = 'name=alex&checks=code1&checks=code2&checks=code3';
parse_str($s, $r);
print_r($r);
Output
Array
(
[name] => alex
[checks] => code3
)
You may think this is wrong because there is only one checks but technically the string is incorrect.
Sandbox
You shouldn't have to post process this data if it's sent correctly, as that is not included in the question, I can only make assumptions about it's origin.
If your manually creating it, I would suggest using serialize() on the form element for the data for AJAX. Post processing this is just a band-aid and adds unnecessary complexity.
If it's from a source outside your control, you'll have to parse it manually (as you attempted).
For example the correct way that string is encoded is this:
name=alex&checks[]=code1&checks[]=code2&checks[]=code3
Which when used with the above code produces the desired output.
Array
(
[name] => alex
[checks] => Array
(
[0] => code1
[1] => code2
[2] => code3
)
)
So is the problem here, or in the way it's constructed...
UPDATE
I felt obligated to give you the manual parsing option:
$str = 'name=alex&checks=code1&checks=code2&checks=code3';
$res = [];
foreach(explode('&',$str) as $value){
//PHP 7 array destructuring
[$key,$value] = explode('=', $value);
//PHP 5.x list()
//list($key,$value) = explode('=', $value);
if(isset($res[$key])){
if(!is_array($res[$key])){
//convert single values to array
$res[$key] = [$res[$key]];
}
$res[$key][] = $value;
}else{
$res[$key] = $value;
}
}
print_r($res);
Sandbox
The above code is not specific to your keys, which is a good thing. And should handle any string formatted this way. If you do have the proper array format mixed in with this format you can add a bit of additional code to handle that, but it can become quite a challenge to handle all the use cases of key[] For example these are all valid:
key[]=value&key[]=value //[key => [value,value]]
key[foo]=value&key[bar]=value //[key => [foo=>value,bar=>value]]
key[foo][]=value&key[bar][]=value&key[bar][]=value //[key => [foo=>[value]], [bar=>[value,value]]]
As you can see that can get out of hand real quick, so I hesitate to try to accommodate that if you don't need it.
Cheers!

PHP instead of printing one array with a few elements, prints number of arrays

I'm playing around with PHP from a couple of months now, I'm trying to print the result of a select query in form of an array, but the issue is that my code's logic isn't correct, and I'm unable to find the problem. Most probably I'm using loops in an inappropriate manner.
I'm using arrays for the first time.
I've done a bit of research, but to no avail.
PHP code:
$data = array();
$selectquery1result = mysqli_query($sqlconnection , $selectquery1);
if (mysqli_num_rows($selectquery1result) > 0) {
while($row = mysqli_fetch_array($selectquery1result)) {
$data[] = $row['U_id'];
print_r($data);
}
}
I've defined $sqlconnection and $selectquery1.
My SQL Server has two records for $selectquery1.
Actual results
Array
(
[0] => 10
)
Array
(
[0] => 10
[1] => 10
)
I don't know why but the number of arrays is the same as the number of rows that should be returned for $selectquery1.
Expected results
Array
(
[0] => 10
[1] => 10
)
So, any help with that would be very helpful for me.
Thanks in Advance!
You are printing your array each iteration of a while loop. Instead you should put your print_r statement outside the loop body.
$data = array();
$selectquery1result = mysqli_query($sqlconnection , $selectquery1);
if (mysqli_num_rows($selectquery1result) > 0) {
while($row = mysqli_fetch_array($selectquery1result)) {
$data[] = $row['U_id'];
}
print_r($data);
}

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 :)

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'

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