I have a multi-dimensional array as follows:
Array
(
[lists] => Array
(
[0] => Array
(
[id] => 23ybdwhdwbed
[name] => TEST
(
[1] => Array
(
[id] => e223edsewed
[name] => TEST 2
(
)
)
I want to access the ID & name variables using a foreach loop.
I'm using this:
$x = 0;
foreach($lists as $list){
$listId = $list[$x]['id'];
$listName = $list[$x]['name'];
echo"$x | $listId $listName <br />";
$x++;
}
For some strange reason, I can only get the value of the first $listId & $name, not the second $listId or $name.
What am I doing wrong here?
You're assuming that you still need to provide the key for each child element. This is not the case.
try
foreach($lists as $list){
$listId = $list['id'];
$listName = $list['name'];
$listId $listName <br />";
}
the foreach() will iterate over them in turn.
if you do need the index number, do this instead.
foreach($lists as $x => $list){
where $x is the index.
The array you posted is wrong because it's missing closing ), so correct that (I think that is TYPO mistake)
After that you need to do it like below:-
foreach($lists['lists'] as $key=> $list){
$listId = $list['id'];
$listName = $list['name'];
echo "$key | $listId $listName <br />";
}
Output:-https://eval.in/846464
Or an one-liner code:-
foreach($lists['lists'] as $key=> $list){
echo "$key | ".$list['id']." ".$list['name']." <br />";
}
Output:-https://eval.in/846465
Your foreach iterates the first, not the second level of your multi dimensional array.
Since the first level only holds the lists array as one and only element the loop only executes once.
Pass the lists key to the foreach instead like so:
$x = 0;
foreach($lists['lists'] as $list) {
echo "$x | " . $list['id'] . " " . $list['name'] . "<br />";
++$x;
}
Also note how in here I reference the list elements by name to make it easier to read.
I think those numerical indexed will just confuse you so try this instead:
$my_array = array(array("id" => "23ybdwhdwbed", "name" => "TEST"), array("id" => "e223edsewed", "name" => "TEST 2"));
To access the values: use:
foreach($my_array as $my_data){
echo "ID:" . $my_data["id"];
echo "<br>";
echo "NAME:" .$my_data["name"];
echo "<br><br>";
}
you just need to do:
foreach($lists['list'] as $listKey=>$listValue){
$listId = $listValue['id'];
$listName = $listValue['name'];
echo"$listKey | $listId : $listName <br />";
}
Try this, I fixed your array structure to work, this is also dynamic so it does not matter how many array you have 0 -> above
$array = array(
'lists' => array(
'0' => array(
'id' => '23ybdwhdwbed',
'name' => 'TEST 1'
),
'1' => array(
'id' => 'e223edsewed',
'name' => 'TEST 2'
)
)
);
foreach ($array as $key => $value) {
for($ctr = 0; $ctr < count($value); $ctr++){
echo 'ID: ' . $value[$ctr]['id'] . '<br>';
echo 'Name: : ' . $value[$ctr]['name'] . '<br><br>';
}
}
Related
How can I put out the following array?
$newdata = array (
'Spiel_ID' => $ausgabeT->Spielplan_ID,
'Heimmannschaft' => $ausgabeVereinT->Name,
'Gastmannschaft' => $ausgabeVereinTGast->Name
);
var_dump($newdata);
foreach($newdata as $result) {
echo $result['Spiel_ID'], '<br>';
}
For the echo I get error:
Illegal string offset 'Spiel_ID'
You are trying to echo a value that doesn't exist.
When you use foreach ($newdata as $result) the $result is a string, not an array.
You have two options, based on this structure:
$newdata = array (
'Spiel_ID' => $ausgabeT->Spielplan_ID,
'Heimmannschaft' => $ausgabeVereinT->Name,
'Gastmannschaft' => $ausgabeVereinTGast->Name
);
Option 1 — Display all values
foreach($newdata as $result) {
echo $result;
}
Option 2 — Display a single value
echo $newdata['Spiel_ID'];
Option 3 — Display Key + Value
foreach($newdata as $key => $value) {
echo $key . ' = ' . $value . '<br>';
}
All you need to do is just echo $result
I would like the data to be echoed out in this format
[0] - [name][description]
[1] - [name][description]
[2] - [name][description]
$options = array('guide_info' => $guide_info);
$guide_info = array( 'guide_name' => $guide_name,
'guide_description' => $guide_description
);
I created two foreach loops to try and echo out the name and description of each, like this:
foreach ($options as $key => $value) {
foreach ($guide_info as $type => $info){
$html .= $type . " " . $info . "\n";
}
}
but I receive errors about invalid argument supplied for foreach() on the second loop.
Currently my print_r($options) shows
Array ( [guide_name] => f
[guide_description] => fff
[0] => Array (
[guide_name] => fsss
[guide_description] => sssss
)
)
and my echo prints
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
guide_name fsss
guide_description sssss
How would I be able to echo out the correct information that print_r is showing?
Use a recursive function to echo out the name and description values in the desired format.
function process_array($arr, $counter){
foreach($arr as $key => $value){
if(is_array($value)){
process_array($value, ++$counter);
}else{
if($key == "guide_name"){
echo "[" . $counter . "] - [" . $value . "][";
}else{
echo $value . "]<br />";
}
}
}
}
// Here $options is your original array
process_array($options, 0);
Output:
[0] - [f][fff]
[1] - [fsss][sssss]
$guide_info = array( 'guide_name' => 'guid name',
'guide_description' => 'guid description',
);
$options = array('guide_info' => $guide_info);
foreach ($options as $key => $value) {
foreach($value as $a => $b) {
echo $a," =",$b ;
}
}
or for print_r
foreach ($options as $key => $value) {
print_r($value) ;
}
Why are you putting the $guide_info in $options.If you want all the entries from $guide_info, you can do this-
for($i = 0; $i < count($guide_info); $i++){
$html .= $type . " " . $info . "\n";
}
-> considering $guide_info is a multidimensional array like = array( [0] => 'guide_name' => $guide_name,
'guide_description' => $guide_description)
If for some reason $guide_info IS important, I would suggest it to be an indexed array not assoc.. Hope you find the solution :)
i want to send more than on array in foreach() .
i know this way is false .whats the true method ?
$Fname = [1,2,3,4,5];
$Lname = [1,2,3,4,5];
$Addrs = [1,2,3,4,5];
$Mobile = [1,2,3,4,5];
$fields = array(
'name' => 'a',
'type' => 'b',
'value' => 'n',
'show' => 'd',
);
foreach($fields as $key => $n)
{
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$key} ,{$n} <br>";
}
If all your arrays have the same number of rows, you can use a for loop instead of a foreach, in conjunction with next() and current() for associative array:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
echo current($fields) . PHP_EOL;
next($fields);
}
The problem is that your arrays haven't same rows number...
So you have to add some condition like this:
for( $i = 0; $i < count($Fname); $i++ )
{
echo $Fname[$i] . PHP_EOL;
echo $Lname[$i] . PHP_EOL;
echo $Addrs[$i] . PHP_EOL;
echo $Mobile[$i] . PHP_EOL;
if( isset(current($fields)) )
{
echo current($fields) . PHP_EOL;
next($fields);
}
}
i know this way is false...? What's false about it?
foreach() will iterate over an array, not over multiple arrays.... if you absolutely need to iterate over multiple arrays within the same foreach() loop, you can use SPL's MultipleIterator, but it adds a lot more complexity to your code, and the approach that you've taken is as good as any
Just make sure that your keys match up in all the arrays; if they don't then you will have problems
foreach(array_values($fields) as $key => $n)
{
$k = array_keys($fields)[$key];
echo " {$Fname[$key]} , {$Lname[$key]},{$Addrs[$key]} , {$Mobile[$key]},{$k} ,{$n} <br>";
}
Instead of storing your data like that, it'd be easier to store it in an array of associative arrays:
$people = array(
array(
'firstName' => 'Bruce',
'lastName' => 'Wayne',
'address' => '123 East St. Gotham City, XX USA'
'mobile' => '847-847-8475'
),
array(
'firstName' => 'Roland',
'lastName' => 'Deschain',
'address' => 'N/A'
'mobile' => '191-919-1919'
)
);
foreach($people as $person){
echo $person['firstName'] + ', ' + $person['lastName'];
echo $person['address'] + ', ' + $person['mobile'];
}
It's just a cleaner way to store/access your data, makes it easy to use one foreach as well.
Try this code
$arr1 = array("a" => 1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);
I have the following code which displays the results that I want. I'm trying to get it to sort on the key 'value' from the output below. So Eric, Eric 2, Eric 3
An example output of $resultnames is:
Array
(
[0] => Array
(
[Eric 2] => Asdf
)
[1] => Array
(
[Eric] => Asdf
)
[2] => Array
(
[Eric 3] => Asdf
)
)
So the key is the first name and the value of that key is the last name. I'm trying to sort the array by first name
foreach (array_chunk($uvugroups, 6, true) as $uvugroup)
{
foreach ($uvugroup as $uvustate) {
echo "<h4>Registrants</h4>";
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array();
foreach ($fnames as $i => $key) {
$resultnames[] = array($key => $lnames[$i]);
}
foreach ($resultnames as $resultname) {
foreach ($resultname as $fkey => $lkey) {
echo "<ul>";
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
echo "</ul>";
}
}
}
}
I tried to use ksort in different places in the code, but it didn't seem to have an effect.
It's a bit hard because the expected output is not defined in the question, but with this code as the contents of the second foreach it should produce a list sorted by first name.
$fnames = explode( '|', $uvustate['fname'] );
$lnames = explode( '|', $uvustate['lname'] );
$resultnames = array_combine($fnames, $lnames);
ksort($resultnames);
echo "<ul>";
foreach ($resultnames as $fkey => $lkey) {
echo "<li>" . $fkey . " " . substr($lkey,0,1) . ".</li>";
}
echo "</ul>";
I have an array that looks like this:
$rowarray(
[0] => [PID] => 97162 [TID] => 340 [StatsID] => 49678
[1] => [PID] => 97165 [TID] => 340 [StatsID] => 49673
[2] => [PID] => 97167 [TID] => 340 [StatsID] => 49675
[3] => [PID] => 97162 [TID] => 340 [StatsID] => 49679
)
Then my code looks like this:
$cntr=0;
foreach($rowarray as $row)
{
echo "<tr><td>$row[PID] $row[TID] $row[StatsID] </td></tr>";
$cntr++;
}
Two things I want to do I want to be able not print the duplicates in the array but print the additional column that has a different value. So my desired output would look like this.
97162 340 49678 49679
97165 340 49673
97167 340 49675
I started out with the array_unique() but that only returned:
97162 340 49678
Assuming only the StatsID changes (not clear from the question)
$map = array();
foreach($rowarray as $row){
$k = $row["PID"] . '-' . $row["TID"];
if( !isset( $map[$k] ) ){
$map[$k] = array();
}
array_push( $map[$k], $row["StatsId"] );
}
foreach($map as $k=>$v){
$row = explode( '-', $k );
echo "<tr><td>$row[0] $row[1] " . implode( " ", $v ) . " </td></tr>";
}
Here's what I'd do:
Start by sorting the array (using usort to sort by PID, then by TID)
Initialize "last" variables ($last_PID and $last_TID). They will store the respective values in the loop
In the loop, first compare the "current" variables to the "last" ones, if they're the same then just echo the StatsID value.
If they're not the same, output the <tr> (but not the final </tr>, so the first part of the loop can add more StatsID values if necessary)
Still inside the loop, after outputting everything, update the "last" variables.
After the loop, output the final </tr>
This may not be optimal, but I'm pretty sure it'll work.
Transfer the $rowarray structure into a map of maps of arrays, like this:
$rowarray = array(
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49678),
array('PID' => 97165, 'TID' => 340, 'StatsID' => 49673),
array('PID' => 97167, 'TID' => 340, 'StatsID' => 49675),
array('PID' => 97162, 'TID' => 340, 'StatsID' => 49679)
);
$keys = array();
foreach ($rowarray as $row) {
if (!is_array(#$keys[$row['TID']])) {
$keys[$rowarray['TID']] = array();
}
if (!is_array(#$keys[$row['TID']][$row['PID']])) {
$keys[$row['TID']][$row['PID']] = array();
}
$keys[$row['TID']][$row['PID']][] = $row['StatsID'];
}
foreach ($keys as $pid => $pid_arr) {
foreach ($pid_arr as $tid => $tid_arr) {
echo "<tr><td>$tid $pid " . implode(' ', $tid_arr) . "</td></tr>";
}
}
See this code in action
As far as I can tell, the only way to do this would be to loop through the array creating a new unique array as you go.
$unique = array();
foreach ($row as $value)
{
$key = $value['PID'];
if (isset($unique[$key]))
{
$unique[$key]['StatsID'] .= ' ' . $value['StatsID'];
}
else
{
$unique[$key] = $value;
}
}
Now, $unique would give you the results you're looking for and you can loop through the unique array and output your results (I also added your counter if needed):
$count = count($unique);
foreach ($unique as $row)
{
echo "<tr><td>{$row['PID']} {$row['TID']} {$row['StatsID']} </td></tr>";
}