looping through multi dimension array - php

I am parsing A JSON file in PHP using PHP Decode
$json= file_get_contents ("resultate.json");
$json = json_decode($json, true);
and then I am trying to loop through the results and display them
foreach($json as $zh){
$name = $zh[0]["VORLAGEN"][0]["JA_PROZENT"];
$JA = $zh[0]["VORLAGEN"][0]["VORLAGE_NAME"];
$kreis = $zh[0]["NAME"];
$kreis1 = $zh[22]["NAME"];
echo $name;
echo $JA;
echo $kreis;
echo $kreis1;
...}
but I receive only one element e.g. position 0 or position 22. I would like to receive all the results and display them in a list. Below you can see the array
Array
(
[GEBIETE] => Array
(
[0] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 205
[STIMMBETEILIGUNG] => 28.11
[NEIN_STIMMEN_ABSOLUT] => 183
[VORLAGE_ID] => 2491
[JA_PROZENT] => 52.84
)
)
[NAME] => Aeugst a.A.
[WAHLKREIS] => 0
[BFS] => 1
)
[1] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 1000
[STIMMBETEILIGUNG] => 26.15
[NEIN_STIMMEN_ABSOLUT] => 851
[VORLAGE_ID] => 2491
[JA_PROZENT] => 54.02
)
)
[NAME] => Affoltern a.A.
[WAHLKREIS] => 0
[BFS] => 2
)
[2] => Array
(
[VORLAGEN] => Array
(
[0] => Array
(
[VORLAGE_NAME] => Kantonale Volksabstimmung über die Vorlage Steuergesetz (StG) (Änderung vom 1. April 2019; Steuervorlage 17)
[JA_STIMMEN_ABSOLUT] => 661
[STIMMBETEILIGUNG] => 30.98
[NEIN_STIMMEN_ABSOLUT] => 454
[VORLAGE_ID] => 2491
[JA_PROZENT] => 59.28
)
)
[NAME] => Bonstetten
[WAHLKREIS] => 0
[BFS] => 3
)
can you please tell me how to print all the elements of this array?

There is GEBIETE layer in your json, so change foreach($json as $zh) to foreach($json["GEBIETE"] as $zh) will works.

You can nest multiple foreach:
$root = $json['GEBIETE'];
foreach ($root as $elem) {
foreach ($elem as $key => $value) {
// VORLAGEN is an array of its own so if you want to print the keys you should foreach this value as well
if(is_array($value)) {
foreach ($value[0] as $k => $v) {
echo $k."\t".$v;
}
}
else {
echo $value;
}
}
}

Related

How to fix this `Illegal string offset` error in php?

I have a multidimensional array as below:
$rows[] = $row;
Now I want to create variable from looping this array. This is how I tried it:
foreach ($rows as $k => $value) {
//echo '<pre>',print_r($value).'</pre>';
$id = $value['news_id'];
$title = $value['news_title'];
echo $title;
}
But it produce an error as below:
...... Illegal string offset 'news_id'
This is the output of - echo '<pre>',print_r($value).'</pre>';
Array
(
[news_id] => 1110
[news_title] => test
[news] => test des
)
1
Array
(
[news_id] => 1109
[news_title] => ශ්‍රී ලංකාවේ ප්‍රථම....
[news] => දහසක් බාධක....
)
1
Can anybody tell me what is the wrong I have done?
UPDATE
output for echo '<pre>',print_r($rows).'</pre>';
Array
(
[0] =>
[1] => Array
(
[news_id] => 1110
[news_title] => test
[news] => test des
)
[2] => Array
(
[news_id] => 1109
[news_title] => ශ්‍රී ලංකාවේ ප්‍රථම....
[news] => දහසක් බාධක....
)
)
1
use isset function because your 0 index is empty in $row
foreach ($rows as $k => $value) {
if(isset($value['news_id'])){
$id = $value['news_id'];
$title = $value['news_title'];
echo $title;
}
}
you should add check (condition) when you assign data to $rows

Get Array value based on object ids with php

I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}

how to combine 2 array values into single one by common value

1.fetching the values from a same table with different date
<?php
$date= date("Y-m-d");;
$prev_date = date('Y-m-d', strtotime($date .' -1 day'));
$result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
$data_yest = array(); // create a variable to hold the information
while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
$data_yest[] = $row_yest; // add the row in to the results (data) array
}
print_r($data_yest);
$result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
$data_today = array(); // create a variable to hold the information
while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
$data_today[] = $row_today; // add the row in to the results (data) array
}
print_r($data_today);
exit;
?>
2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp
Array (
[0] => Array ( [isp] => aol [sent_yest] => 46838 )
[1] => Array ( [isp] => gmail [sent_yest] => 33015 )
[2] => Array ( [isp] => juno [sent_yest] => 93544 )
[3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
[4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)
Array (
[0] => Array ( [isp] => aol [sent_today] => 14135 )
[1] => Array ( [isp] => att [sent_today] => 624 )
[2] => Array ( [isp] => gmail [sent_today] => 21263 )
[3] => Array ( [isp] => juno [sent_today] => 74934 )
[4] => Array ( [isp] => roadrunner [sent_today] => 939 )
[5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)
Now i need a result like this isp name, yesterday's sent count, today's sent count
[isp, sent_yest, sent_today],
[aol, 46838, 14135],
[att, 0, 624],
[gmail, 33015, 21263],
Anyone help me to solve this.. Thanks in advance
Do it like below:-
$final_array = array();
if(count($arr1)>=count($arr2)){
foreach ($arr1 as $arr){
$key='';
foreach ($arr2 as $ar2){
if($arr['isp'] == $ar2['isp']){
$final_array[$arr['isp']] = array($arr['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $arr['isp'];
}
}
if($key!==''){
$final_array[$key] = array($arr['isp'],$arr['sent_yest'],0);
$key ='';
}
}
}
if(count($arr2)>count($arr1)){
foreach ($arr2 as $ar2){
$key='';
foreach ($arr1 as $arr){
if($ar2['isp'] == $arr['isp']){
$final_array[$ar2['isp']] = array($ar2['isp'],$arr['sent_yest'],$ar2['sent_today']);
$key ='';break;
}else{
$key = $ar2['isp'];
}
}
if($key!==''){
$final_array[$key] = array($ar2['isp'],0,$ar2['sent_today']);
$key ='';
}
}
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/814625
I would avoid foreach if it's possible, since it leads to code that's much harder to understand. With array operation it can look like this:
// First we merge the two arrays
$merged = array_merge($data_yest, $data_today);
// Then format it
$final = array_reduce($merged, function($final, $item) {
// Initialize for each isp if it's not present
// This way we avoid overwriting previous data and have a default value 0
if (! isset($final[ $item['isp'] ])) {
$final[ $item['isp'] ] = [
'sent_yest' => 0,
'sent_today' => 0,
];
}
// And if one of the days is present, we add it
if (isset($item['sent_yest'])) {
$final[ $item['isp'] ][ 'sent_yest' ] = $item['sent_yest'];
}
if (isset($item['sent_today'])) {
$final[ $item['isp'] ][ 'sent_today' ] = $item['sent_today'];
}
// Then return the modified array
return $final;
}, []);
print_r($final);
exit;
Result looks like this:
Array
(
[aol] => Array
(
[sent_yest] => 46838
[sent_today] => 14135
)
[gmail] => Array
(
[sent_yest] => 33015
[sent_today] => 21263
)
[juno] => Array
(
[sent_yest] => 93544
[sent_today] => 74934
)
[roadrunner] => Array
(
[sent_yest] => 6181
[sent_today] => 939
)
[yahoo] => Array
(
[sent_yest] => 71444
[sent_today] => 22059
)
[att] => Array
(
[sent_yest] => 0
[sent_today] => 624
)
)

Display element from array before looping

I need to display a certain object from an array before showing the rest of the array.
The array looks like this:
Array
(
[0] => stdClass Object
(
[template_id] => 91
[template_name] => Alphabet
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821665
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[1] => stdClass Object
(
[template_id] => 92
[template_name] => Blank Template
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821670
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[2] => stdClass Object
(
[template_id] => 31
[template_name] => Holiday Specials
[template_thumbnail] => accommodation-1-20110926.jpg
[template_create_date] => 1456821660
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => Accommodation
[sort] => 3
)
)
I need to show Blank Template first and then show the rest alphabetically (the order it is in now.
Is there a more elegant solution than looping through the array twice? The size of the array can be anything from 1 (the blank template) to countless objects.
$str="";
for($i=0;$i<=count($arr);$i++){
if($arr[$i]['template_name'] == "Blank Template"){
echo $arr[$i]['template_name'];
}else{
$str .= $arr[$i]['template_name']. "<br>";
}
}
echo $str;
Try this:
$firstItem = null;
$outArray = [];
foreach($yourArray as $item){
if($item->template_name == 'Blank Template'){
$firstItem = $item;
}else{
$outArray[$item->template_name] = $item;
}
}
ksort($outArray,SORT_STRING);
array_unshift($outArray,$firstItem);
Just one loop. Pay attention that this way of doing things, just work if you have uniqueness on the template_name!
Hope it helps.
This will work for you, try
<?php
$dataArray = array(0=>array('template_id'=>91,'template_name'=>'Alphabet'),
1=>array('template_id'=>92,'template_name'=>'Blank Template'),
2=>array('template_id'=>31,'template_name'=>'Holiday Specials')
);
$newArray = array();
foreach($dataArray as $key => $val)
{
if(in_array('Blank Template',$val))///find the key for black template
{
unset($dataArray[$key]); ///unset black temp from original array
$newArray[] = $val;///push black temp into new array at 0 index
foreach($dataArray as $k => $v)
{
$newArray[] = $v; ///push the renaming values into new array
}
}
}
echo "<pre>"; print_r($newArray);
?>
This will give you :
Array
(
[0] => Array
(
[template_id] => 92
[template_name] => Blank Template
)
[1] => Array
(
[template_id] => 91
[template_name] => Alphabet
)
[2] => Array
(
[template_id] => 31
[template_name] => Holiday Specials
)
)
LIVE EXAMPLE : CLICK HERE

How to iterate over a multidimensional array?

I have array like this. This array is created dynamically
Array
(
[Data NotUploading] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => A
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
[1] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
)
)
[Battery Problem] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-03
[issue_id] => 3
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Battery Problem
)
)
)
)
What I need to do is to use 2 foreach or 1 foreach & 1 for loop so that I can get each value of date I did like this
foreach($gResultbyName as $key1 => $rec){
for($j = 0;$j<count($rec);$j++ ){
echo $rec['items'][$j]['date'];
}
}
but its only retrieving 2013-04-02 & 2013-04-03 that is 0 index date of data NotUploading & 0 index date of Battery Problem. Basically I need to compare each value and others stuff but I just cant get each date value.
Forgive me for ignorance but I tried a lot :(
try this:
foreach ($data as $d)
{
foreach($d['items'] as $item)
{
echo $item['date'];
}
}
Your for-loop loops count($rec) times, but should count($rec['items']).
This should load the dates into an array sorted by the issue_name. The you can step through them for further processing.
$dates= array();
foreach ($gResultbyName AS $events){
foreach ($events['items'] AS $item){
$dates[$item['issue_name']][] = $item['date'];
}
}
var_dump($dates);

Categories