I try to add new data in a multidimensional array for each loop, but it wont work.
This shows the values in my array:
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
$klanten['newData'] = 'test';
}
}
With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.
I also tried to use this, AFTER the script above:
foreach ($klanten as &$item ){
$item['newData'] = 'test';
}
That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?
Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
// $klanten['newData'] = 'test'; // instead of this
$klanten[$key]['newData'] = 'test'; // do this
}
}
This will save each and every value of newData index according to its key in $klanten array.
Related
So, I wanna select item per item from this array ["A185","A740","A540"]
Like for example I wanna select
$cie[0] = A185 or A740
with something like $cie[0] = A185
This is my code so far, since I fetch that code from a row in a MySQL table.
while ($row = pg_fetch_array($resul)) {
$cie10 = array($row["cie"]);
}
$cie = ["A185","A740"];
$values = array_count_values($cie);
$top = array_slice($values, 0, 1);
print_r($top);
What I get:
Array ( [["A185","A740","A540"]] => 1 )
It just won't work.
I'm Sure you are looking to display the data that is in the array variable
$var = ["A185","A740","A540"]; // Asume as you stored the values in the array called var
foreach($var as $x){
print_r($x);
echo "<br/>";
}
EDIT: Highlighted the code
If i understand your problem. You are looking for this:-
$Fullarray = ["A185","A740","A540"];
$cie = array_slice($Fullarray,0,2);
foreach ($cie as $name) {
$d[] = '"' . $name . '"';
}
$implodekeys = "[".implode(',',$d)."]";
$newarray[$implodekeys] =1;
echo "<pre>"; print_r($newarray);
Hope it helps!
I'm trying to capture a user's checkbox selection from a dynamically generated list of options but I'm getting "Array" instead of the names selected.
In my last test, I checked 2 of the three boxes and got 3 instances of "Array" back.
This is my query that finds the names:
$query = "SELECT id, first_name, last_name
FROM users WHERE location_id = " . $location_id;
$result = mysqli_query($connection, $query);
if (!$result)
{
die("Database query failed: " . mysqli_error($connection));
}
while ($row = mysqli_fetch_array($result))
{
$name = $row['first_name'] . " " . $row['last_name'];
echo '<label><input type="checkbox" name="emp_name[]" id="emp_name[]" value="' . $name . '"> ' . $name . '</label>';
}
I then post the array of names like this:
$attendee = $_POST['emp_name'];
And try to generate the list of names for my email like this:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
Can someone help me see what's wrong?
I changed my code and included a part of the html that I'm trying to render:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
But it still returns Array.
Not sure why you do this:
$attendee = (array)$_POST['emp_name'];
Try to replace it with:
$attendee = $_POST['emp_name'];
From your question it's not too clear, but I think you're creating an array within an array,and that that's the issue.
If the above doesn't help, try to var_dump() the variable that gives you "Array" response, and you'll see what's within it.
EDIT: In addition to the change above, try to make this change too:
Replace all this code:
$values = ('emp_name');
foreach ($values as $value) {
$$value = (array)$_POST[$value];
}
for($i = 0; $i < count($attendee); $i++){
$attendees = array();
foreach ($values as $value) {
$attendees[] = ${$value}[$i];
}
with:
foreach ($_POST['emp_name'] as $name) {
$attendees[] = $name;
}
EDIT #2:
According to your code:
foreach ($attendee as $name) {
$attendees[] = $name;
$htmlBody .= "<tr><td>{$attendees}</td></tr>";
}
It's totally normal that you're getting Array instead of a name. See, by writing:
$attendees[] = $name;
you're implying to php that it's an array. On the other hand the foreach loop does the opposite thing, it takes each of the values from $attendee array and makes it available to you as $name variable. So you're basically doing the right thing, and then reverting it back to array for no reason.
SOLUTION:
Replace {$attendees} with {$name}. And it should work.
You can write that with alot less code.
$attendees will now contain your checked checkboxes.
$attendees = array()
foreach($_POST['emp_name'] as $name){
$attendees[] = $name;
}
I have dateValues as follows,
[dateVals] = 031012,041012;
it is comma seperated values. I want to make this as array and to get individual values . As i am new to PHP , i want some one's help .
$val = array[dataVals];
for($i=0;$i<sizeof($val);$i++) {
echo "val is".$val[$i]."\n";
}
is not working
use this code
$dateVals = '031012,041012';
$pieces = explode(",", $dateVals);
for($i=0;$i<sizeof($pieces);$i++) {
echo "val is".$pieces[$i]."\n";
}
it will give you proper output.
working example http://codepad.viper-7.com/PQBiZ3
$dateVals = '031012,041012';
$dateValsArr = explode(',', $dateVals);
foreach( $dateValsArr as $date) {
}
Try this code.
Try this One
$dateVals = '031012,041012';
$date_arr[] = explode(',',$dateVals);
for($i = 0 ; $i < count($date_arr) ; $i++)
{
print $date_arr[$i].'<br />';
}
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) ;
}
Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;