Array in Array in Array - Cant get data from JSON String - php

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>';
}
}
}

Related

how to modify array_count_values output

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);

How can count duplicate array value in php?

I have an array with duplicate values.
I want print all items but also for duplicate value, I want print a number too.
Like this:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana')
foreach($arr as $name)
{
echo $name;
}
How can print this result:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
This should work for you:
Here I first use array_slice() to get an array of all elements which are before the current element of the iteration, e.g.
iteration value | sliced array
-----------------------------------
sara | []
jorj | [sara]
Then I use this array with array_filter(), to only keep the values with are equal to the current iteration value, so I can tell how many of the same values are in the array before the current value.
Now I simply have to count() how many there are and if there are more than 1 we also print it in the output.
Code:
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
foreach($arr as $key => $name) {
$count = count(array_filter(array_slice($arr, 0, $key), function($v)use($name){
return $v == $name;
})) + 1;
echo $name . ($count > 1 ? " - $count" : "") . PHP_EOL;
}
output:
sara
jorj
sara - 2
sara - 3
jorj - 2
eli
ana
Maybe Im little bit late to this answer, but heres my attempt
$arr = array('sara','jorj','sara','sara','jorj','eli','ana');
$tmp = array();
foreach ($arr as $value) {
if (!isset($tmp[$value]) ) {
// if $value is not found in tmp array
// initialize the value in tmp array and set to 1
$tmp[$value] = 1;
echo $value;
}
else {
// found the value in tmp array
// add 1 to the value in tmp array
// output its current total count of this value
$tmp[$value] += 1;
echo "$value-", $tmp[$value];
}
echo "<br>";
}
output:
sara
jorj
sara-2
sara-3
jorj-2
eli
ana
This actually has the same output of array_count_values, but broken into pieces of how it forms...I think

How to find the first, second, third etc numbers of an array

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo

Duplicate array values not working with Simple HTML DOM

I'm working with Simple HTML DOM like this:
foreach($html->find('img', 18) as $d) {
echo $d->outertext;
}
Now I want to implement an array of variables, in this case images, so I did:
$img=array(
"img"=>"18",
"img"=>"21"
);
foreach($img as $x=>$x_value)
{
$d = $html->find($x, $x_value);
echo $d->outertext;
}
The problem is that Simple HTML DOM is only returning the last image in array, which is number 21. What do I have to do to make it return everything in the array?
It's because both items in your $img array has the same key. foreach doesn't recognize them as two seperate items because both keys are img.
Example code to demonstrate:
$test = array(
"key" => 1,
"key" => 2
);
echo "Length of array: " . count($test) . "\n\n";
echo "Items in array:\n";
foreach($test as $key => $value) {
echo "$key => $value\n";
}
Outputs:
Length of array: 1
Items in array:
key => 2

Print array with for loop

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 />";
}
?>

Categories