I want to print this array to all indexes upto 21, but in this code this is printing only to array length, what i should i do the print whole array in for loop?
<?php
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$length=count($array);
for($i=0;$i<$length;$i++){
echo "$i=>".$array[$i];
echo "<br />";
}
?>
Your difficulty is the way you're defining your array:
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
Arrays in php are really hashmaps; when you call index 5 on the above array, it is undefined. No index item up to 20 will be defined, and these will Notice out:
PHP Notice: Undefined offset: 5
Because you're using array length as your iterating variable, and calling exactly that variable, you will never get positions 20 and 21 in your code.
This is what your array looks like to the computer:
0 => "hello"
1 => "world"
2 => "this"
3 => "is"
4 => "an"
5 => NULL
6 => NULL
7 => NULL
... //elided for succinctness
19 => NULL
20 => "array"
21 => "code"
When you call $array[7] it can't return anything. When you call $array[20] it will return "array".
What you really want is a foreach loop:
foreach($array as $key => $val) {
//key will be one of { 0..4, 20..21}
echo "$key is $value\n";
}
Resulting in:
$ php test.php
0 is hello
1 is world
2 is this
3 is is
4 is an
20 is array
21 is code
If you must use a for loop:
$key_array = array_keys($array);
for($i=0;$i<count($key_array);$i++){
$key = $key_array[$i];
echo "$key => ".$array[$key]."\n";
}
Note this is not a clean solution.
Solution with a for loop:
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$max = max(array_flip($array)); // What if max array key is 10^5 ?
for($i=0;$i<=$max;$i++){
if(isset($array[$i])){
echo "$i=>".$array[$i]."<br>";
}
}
foreach($array as $key=>$value){
echo $key."=>".$value;
echo "<br />";
}
You want to start your loop with $i=0 as PHP uses zero indexing. also in your loop you want to cap your max value for interation at $i
<?php
$array=array(0=>"hello",
1=>"world",
2=>"this",
3=>"is",
4=>"an",
20=>"array",
21=>"code" );
$length=count($array);
for($i=0;$i<$length;$i++){
echo "$i=>".$array[$i];
echo "<br />";
}
?>
Related
Original Post: Objects in Arrays...
The data I provided was only one line. I have many lines of the same with different "Bestaende" and "Menge":
[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]
The foreach you describe I understand, but it doesn't work as expected .
$jsonarray = json_decode($jsonfile,true);
echo 'Array 0 Menge: '.$jsonarray['0']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 1 Menge: '.$jsonarray['1']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 2 Menge: '.$jsonarray['2']['Bestaende']['0']['Menge'].'<br>';
echo 'Array 3 Menge: '.$jsonarray['3']['Bestaende']['0']['Menge'].'<br>';
brings out
Array 0 Menge: 1
Array 1 Menge: 1
Array 2 Menge: 1
Array 3 Menge: 1
Okay. But when I try to foreach it (because I have a list of base data), the output is only one row. I get only one entry "1". Nothing more.
$x=0;
foreach($jsonarray[$x]['Bestaende'] as $idx => $Bestaende) {
echo 'Print Menge: ';
print_r($Bestaende['Menge']);
$x++;
}
So I try to loop over the Array to get the data. The Result is:
Array ( [Filiale] => 1 [FilialeBez] => Laden [Menge] => 1 [Gln] => [Dispo] => 0 )
Print Menge: 1
I have a problem with the array in array in array ... Is there a better way to get the data I want?
Or is my foreach loop wrong?
You loop only over $jsonarray[0]['Bestaende'] which only contains one item. You should loop over $jsonarray and from there dive in deeper.
foreach($jsonarray as $item) {
echo 'Print Menge: ';
print_r($item['Bestaende']['0']['Menge']);
// or even dive in deeper
foreach ($item['Bestaende'] as $bestaende) {
// .. $bestaende['Menge'];
}
}
Try it like this
foreach($jsonarray as $k=>$alldata)
{
foreach($alldata["Bestaende"] as $idx => $Bestaende)
{
echo '<pre>';
echo 'Print Menge: '.$Bestaende['Menge'];
echo '</pre>';
}
}
Try this code..
$j = '[{"Ean":"","Barcode":"010241770148","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770149","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770151","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90},
{"Ean":"","Barcode":"010241770152","Bezeichnung":"Richard 1516","Bestaende":[{"Filiale":1,"FilialeBez":"Laden","Menge":1,"Gln":null,"Dispo":0}],"Bestand":1,"Dispo":0,"Uvp":269.90,"Vk":269.90}]';
$a = json_decode($j,true);
foreach($a as $key => $value){
if(!empty($value['Bestaende'])){
foreach($value['Bestaende'] as $k=>$v){
echo 'Print Menge: '.(!empty($v['Menge']) ? $v['Menge'] : '').'</br>';
}
}
}
i have an array
$array=(1,1,2,3,3,3,4);
i need to find each element how many times each element is exist in array .
So that i use
$occurences = array_count_values($array);
output is
Array
(
[1] => 2
[2] => 1
[3] => 3
[4] => 1
)
But i need to arrage the out put in following format
1 : 2
2 : 1
3 : 3
4 : 1
how can i do that ?
is there an other solution rater than using array_count_values
please help ;
Use foreach to iterate over every occurance and echo them out.
// If they are in wrong order, sort your array
ksort($occurences);
// Print output
if(count($occurences)>0){
foreach ($occurences as $key => $value) {
echo $key.' : '.$value.'<br />';
}
}
EDIT
To sort by no of occurances, use arsort.
arsort($occurences);
Of course, before printing it.
If 2:1 must come before 4:1 in your case, use:
asort($occurences);
arsort($occurences);
Just use this loop to have output like you need
foreach ($occurences as $k => $v) {
echo "$k : $v <br>";
}
You can use json_encode or array_keys and array_values
<?php
$array= array(1,1,2,3,3,3,4);
$occurences = array_count_values($array);
$array_keys = array_keys($occurences);
$array_values = array_values($occurences);
for($i=0; $i<count($array_keys); $i++) {
echo $array_keys[$i].':'.$array_values[$i].'\n';//add \n or \br tag
}
//you can echo json_encode
echo json_encode($occurences);
Hello guys i have coded something like this ..I just dont know wheather the code is right or not ..But i have a question
THe code is
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $value['name'];
}
I know that value of name can be acessed by $featured['name']
but now I just need to know wheather the key of array can be acessed with value like $value['name'].
Is it possbile like that ?..
Any help would be appreciated ..Thanks
$featured = array('name' => 12,'yeah' => 10);
foreach($featured as $key => $value){
echo $key; // outputs: name
echo " - ";
echo $value; // outputs: 12
echo "<br />";
}
Yes, it supports that in the next iteration of the loop.
Output:
name - 12
yeah - 10
BTW, one more way of accessing the keys from array.
$featured = array('name' => 12,'yeah' => 10);
while (current($featured)) {
echo key($featured).'<br />';
next($featured);
}
Output:
name
yeah
You most probably want to do:
echo "{$key} => {$value}";
The foreach($featured as $key => $value) statement iterates the array and for each iteration $key and $value contain both the key and value for the tuple.
Take a look at this:
http://php.net/array_search
it searches for the value and returns it's key.
It's not like accessing $array['value'] but it's still userfull if you want to find the key.
How to access all the elements under each key of multidimensional array.
$multi = array
(
"Abhishek" => array("Choudhary", "Bunta", "Popy"),
"Bond" => array("One", "two", "three", "four"),
"Super" => array("T1", "T2")
);
$data = array("Abhishek","Bond","Super");
for($j = 0;$j<count($data);$j++)
{
echo "<br/>Main Array Value ".$data[$j]."<br/>";
for($i = 0;$i<count($data[$j]);$i++)
{
echo "sub Value ".$multi[$data[$j]][$i]." count ".count($data[$j]) ;
}
}
Now I want to iterate through each element of Abhishek , Bond and Super , so we can see Abhishek has 3 elements inside it but $data[$j] always return 1. If I increment then I can access Bunta
Currently the output is -
Main Array Value Abhishek
sub Value Bunta
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
and expected is:
**
Main Array Value Abhishek
sub Value choudhary
sub Value Bunta
sub Value Popy
:
:
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
**
Disclaimer : I am super new to PHP so may be my expectation can be invalid or I am missing some very silly thing.
i recommend you read some articles about multidim arrays, anyway your needs could be done with following code:
foreach($multi as $key => $value) {
echo "<br/>Main Array Value ".$key."<br/>";
for($i = 0; $i < sizeof($value); $i++) {
echo "sub Value ".$value[$i]." count ".sizeof($value) ;
}
}
PS: you don't need $data array
#bunta please check this out: PHP Foreach
You could use foreach instead.
Also:
PHP foreach loop through multidimensional array
HTH.
Using foreach() would be easier
foreach ($multi as $key => $subarray)
{
echo $key . '<br />';
foreach ($subarray as $subvalue)
{
echo ' - '.$subvalue . '<br />';
}
}
Will output
Abhishek
- Choudhary
- Bunta
- Popy
Bond
- One
- two
- three
- four
Super
- T1
- T2
Try this :
<?php
foreach($multi as $key => $value) {
echo "<br/>Parent Value ".$key."<br/>";
for($i = 0; $ < sizeof($value); $++) {
echo "Child Value ".$value[$i]." count ".sizeof($value) ;
}
}
?>
You are using wrong syntax to access it.
Thanks
All you need is use foreach to iterate on $multi array (if you just want to know the number of subelements for each element level 1):
<?php
echo "<br\>multiDimensional Array<br\>";
$multi = array("Abhishek" =>array
("Choudhary",
"Bunta",
"Popy"),
"Bond" => array
("One",
"two",
"three",
"four"),
"Super" => array
("T1",
"T2")
);
foreach( $multi as $value ){
echo " count ".count($value) ;
}
When using an array in a foreach loop
$stdlist = rtrim(trim($_POST['stdlist'], '/'), '/');
$stdlist = explode('/' , $stdlist);
print_r($stdlist);
foreach($stdlist as $value)
{
echo "<br>";
echo $_POST[$value];
}
the array $stdlist is clearly working; when printed this returns:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 8 )
My problem is that when I use the foreach loop to extract out of the array one value at a time, the following gets printed to the page:
4
4
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
Notice: Undefined offset: 7 in C:\Program Files\wamp\www...on line 35
I know this isn't functioning as intended as I am expecting the following:
1
6
7
8
Could somebody please explain why this is happening and how to fix this issue? Thanks :-)
You have to print the $value bacause $value have original array value not index.
And you are getting array in $stdlist from exploding this post variable $_POST['stdlist'].
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
Now you will get your required result.
instead of using echo $_POST[$value]; just use echo $value when you use foreach loop for an array, the values on each nodes are automatically extracted.
foreach ($array as $index=>$value){
echo "index is $index and value associated with it is $value.";
}
Hope this helps.
foreach($stdlist as $value)
{
echo "<br>";
echo $value;
}
when you use foreach the $value is not the position in the array, if you want to use the position you need to do
for($pos=0; $pos<sizeof($stdlist); $pos++)
{
echo "<br>";
echo $stdlist[$pos];
}
When using the foreach() loop, I'd recommend assigning both the position and value to their own respective variables and then print them to the screen to see how the foreach loop has assigned the values.
foreach( $stdlist as $position => $value ) {
echo "The current position is $position, and the value of \$stdlist[$position] is
$value";
}