How to return all array values inside foreach loop. Return is working fine and no error but is only one record. If i have 10 records in database, It supposed to be all records. What did i missed this code? thanks for your help.
PHP
function myfunction(){
$query ="SELECT * from tbl_data";
$stmt = $this->getConnection()->prepare($query);
$stmt->execute();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array = array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]);
}
return $array;
}
You are currently actually just overwriting $array, you need to push the new data to it instead.
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
$array[] = [
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
];
}
return $myArray;
You are assigning $array on every iteration, overwriting the previous value.
Maybe you want to create an array of arrays:
$array = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($array, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $array;
You are only getting one value returned because you are overwriting the value of the array each time.
You need to push the new values each loop iteration.
$myArray = array();
foreach ($stmt->fetchAll() as $value) {
//custom value
$customval = 1;
array_push($myArray, array([
"ID" => $value['ID'],
"name" => $value['name'],
"staus" => $value['status'],
"customval" => $customval,
]));
}
return $myArray;
This will return an array of arrays.
Related
I have an array called $arr containing some information about users. Using $arr I want to create a new associative array with specific keys. That's what I got so far:
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
What I'm trying to achieve is a new array that has the following format:
'first_key_name' => $val->ID
'second_key_name' => $val->login
'first_key_name' => $val->ID
'second_key_name' => $val->login
The problem with my current approach is when I var_dump($groups) I only get one key with an empty value although the array should contain at least 10 entries.
The output of var_dump($groups):
array:1 [▼
"first_key_name" => "4"
]
What am I doing wrong?
You are overwriting your variables each time round the loop in this code
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
So instead do
$groups = [];
foreach($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID
'second_key_name' => $val->login
];
}
This will create something like this
[0]
[
'first_key_name' = 1,
'second_key_name' = 99
]
[1]
[
'first_key_name' = 2,
'second_key_name' = 199
]
etc
You approach is overwriting the key value every time. That's why you need to use 2d array.
You can try like this:
$groups = [];
foreach($arr as $val) {
$groups[] = ['first_key_name' => $val->ID, 'second_key_name' => $val->login];
}
What happens here, is you are overwriting first_key_name and second_key_name in each turn of the loop. But you want to get an array with the new key=>value pairs.
To achieve that you have to append a new item to your array called $groups, like this:
$groups = [];
foreach ($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID,
'second_key_name' => $val->login
];
}
You may also use array_map for this:
$groups = array_map(function ($val) {
return [
'first_key_name' => $val->ID,
'second_key_name' => $val->login,
];
}, $arr);
I have loop like this
foreach($this->input->post('users') as $value)
{
foreach($this->input->post('group_name') as $v)
{
echo $value.','.$v.'<br>';
}
}
And its ouput is
17,5
17,6
18,5
18,6
19,5
19,6
20,5
20,6
Now i want to create an associative array like this using the above values.
array(
array(
'user_id' => 17,
'group_id' => 15
),
....
....
array(
'user_id' => 20,
'group_id' => 6
)
)
How can i do that
I've tried this in foreach loop but it will print two separate arrays.
$temp['user_id'][]=$v;
$temp['group_id'][]=$value;
All you have to do is append array with respective values.
$result = [];
foreach($this->input->post('users') as $value)
{
foreach($this->input->post('group_name') as $v)
{
$result[] = ['user_id' => $value, 'group_id' => $v];
}
}
var_dump($result);
This loop should help you out.
$resultArray = [];
foreach($this->input->post('users') as $value) {
foreach($this->input->post('group_name') as $v) {
$resultArray[] = array(
'user_id' => $value,
'group_id' => $v,
);
}
}
var_dump($resultArray);
It's very simple, you just have to append/push the child array into main array.
Like this,
$main_array=array();
foreach($this->input->post('users') as $value)
{
foreach($this->input->post('group_name') as $v)
{
$group_array=array();
$group_array["group_id"]=$v;
$group_array["user_id"]=$value;
$main_array[]=$group_array;
//echo $value.','.$v.'<br>';
}
}
print_r($group_array);
You may also use array_push() to push child array into main array.
Syntax for that would be,
array_push($main_array, $child_array);
Can u try this
$temp = array();
foreach($this->input->post('users') as $key=>$value)
{
foreach($this->input->post('group_name') as $v)
{
$temp[$key]['user_id']=$v;
$temp[$key]['group_id']=$value;
}
}
print_r($temp);
Can someone explain to me why this isn't working? I'm trying to push an array into another array, but its only coming back with the last item from the $votes array.
foreach($json['area'] as $row) {
$name = $row['name'];
$group = $row['array']['group'];
$majority = $row['array']['majority'];
$candidates = $row['array']['candidates'];
foreach ($candidates as $candidate) {
$vote = $candidate["votes"];
$candi = $candidate["name"];
$votes = array("vote" => $vote, "candidate" => $candi);
}
$array = array("name" => $name, "group" => $group, "majority" => $majority, "votes" => $votes);
$results[] = $array;
}
Each iteration of the outer loop is only producing a single $votes array , seemingly for a single candidate, in this line:
$votes = array("vote" => $vote, "candidate" => $candi);
If you want to capture multiple entries in that array for each row, you need to make it a multi-dimensional array also:
$candidates = $row['array']['candidates'];
$votes = [];
foreach ($candidates as $candidate) {
$votes[] = array(
"vote" => $candidate["votes"],
"candidate" => $candidate["name"]
);
}
$array = array(
"name" => $name,
"group" => $group,
"majority" => $majority,
"votes" => $votes
);
I was wondering when working with multimedional arrays, if a certain key is the same, is there a way to combine the contents of other keys into its own array if a certain key is the same?
Something like this:
// name is the same in both arrays
array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
)
into something like this
array(
array(
'name' => 'Pepsi',
'store' => array('Over here', 'Over here'),
'number' => array('1234567', '5556734')
)
)
The defining key is checking if the name element is the same for the other arrays.
You can try a function like this.
function mergeByKey($array,$key){
$tmp_array = array();
foreach ( $array as $k => $row ) {
$merged = false;
foreach ($tmp_array as $k2 => $tmp_row){
if ($row[$key] == $tmp_row[$key]){
foreach ( $row as $k3 => $value ) {
if ($k3 == $key) continue;
$tmp_array[$k2][$k3][] = $value;
$merged = true;
}
}
if ($merged) break;
}
if (!$merged) {
$new_row = array();
foreach ( $row as $k4 => $value ) {
if ($k4 == $key) $new_row[$k4] = $value;
else $new_row[$k4] = array($value);
}
$tmp_array[] = $new_row;
}
}
foreach ( $tmp_array as $t => $row ) {
foreach ( $row as $t2 => $value ) {
if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
}
}
return $tmp_array;
}
passing the array as first parameter and the key as second one.
I'm referencing to your array structure
edited: missed a piece
edited2: if resultin array contains elements with one string, it returns a string and not a array with one element
demo
This function uses a given field name as the grouping identifier and turns all other fields into arrays.
Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)
$arr = array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
);
function mergeArray($array, $column)
{
$res = array();
foreach ($array as $item) {
foreach ($item as $key => $value) {
if ($key === $column) {
$res[$column][$key] = $value;
} else {
$res[$column][$key][] = $value;
}
}
}
return array_values($res);
}
print_r(mergeArray($arr, 'name'));
Demo
Thanks to Gianni Lovece for her answer but I was able to develop a much simpler solution based on this problem. Just plug in the $result_arr to browse through and the $key you want to use as basis and it immediately outputs a multidimensional array with non-repeating values for repeating elements (see example below).
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
For example, in the sample array for this question, running multiarray_merge($mysample, 'name') returns
array(
'Pepsi' => array(
'name' => 'Pepsi',
'store' => 'Over here', // String: Not an array since values are not unique
'number' => array('1234567', '5556734') // Array: Saved as array since values are unique
)
);
I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}