How to store values from foreach loop into an array? - php

Need to store values from foreach loop into an array, need help doing that.
The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated.
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);

Declare the $items array outside the loop and use $items[] to add items to the array:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);

Use
$items[] = $username;

Try
$items = array_values ( $group_membership );

<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>

You can try to do my answer,
you wrote this:
<?php
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
?>
And in your case I would do this:
<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
$items[] = $username;
} ?>
As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)
<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
$items[] = $username;
}
?>
while is faster, but the last example is only a result of an observation. :)

This is how you do it:
foreach($orders as $item){
$transactionIds[] = $item->generated_order_id;
}
dump($transactionIds);
This is assuming $orders collection has a field called 'generated_order_id'.

$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
Just try the above in your code .

Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);

this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>

Related

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Fetch an array into another array PHP

i want to fetch an array into another array without using foreach
$data[0]['name']="name1";
$data[0]['age']=10;
$data[1]['name']="name2";
$data[1]['age']=11;
$data[2]['name']="name3";
$data[2]['age']=12;
i want to fetch array $data into $user so that $user become..
$user['name']="name1";
$user['age']=10;
without using 'foreach' statement.
Without foreach you say...
reset($data);
$max = count($data);
for ($i = 0; $i < $max; $i++) {
list($key, $user) = each($data);
// do stuff.
}
You can use this:
$user = $data[0];
No foreach loop:
<?php
while( $user = array_shift( $data ) ) {
print_r( $user );
}
But then, why do you have such an odd requirement? After all, foreaches are just the tool for a job like this. Are we, by any chance, doing your homework? ;)
foreach actually represents for and each:
for (reset($data); list($key, $user) = each($data);) {
### ####
// do stuff.
}

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

php string name as variable in array

how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/

Multi dimensional array

Have just come across a problem where I believe this is the solution.
At the moment I have the following code:
function siteUsers()
{
global $database;
$q = "SELECT username, id FROM ".TBL_USERS."";
return mysql_query($q, $this->connection);
}
function generateUserArray()
{
$u = array();
$i = array();
$result = $this->siteUsers();
while( $row=mysql_fetch_assoc($result))
{
$u[] = $row['username'];
$i[] = $row['id'];
}
return $u, $i;
}
As you can see, when I then go onto use foreach, the u and i get split apart.
Is there anyway that I could keep them together?
foreach ($u as $username) {
echo"<option value='$i'>$username</option>";
}
What I need it the option value to be the id and the visual value to be the username.
Is this possible?
Thanks
Use an associative array linking the ID to the username. I'm assuming here the IDs are unique.
$users = array();
while( $row=mysql_fetch_assoc($result))
{
$users[$row['id']] = $row['username'];
}
return $users;
Then:
foreach ($users as $id => $username)
{
echo "<option value='$id'>$username</option>";
}
foreach($u as $idx => $username)
{
echo"<option value='".$i[$idx]."'>$username</option>";
}
assuming equal length and that php function can return two values :\

Categories