Read from JSON file with PHP and Multiple foreach statements - php

I tried to read from a JSON file using PHP. But I am stuck now.
This is my JSON file :
Array
(
[date] => 25-1-2017
[leagues] => Array
(
[0] => Array
(
[league_id] => 0
[league_name] => كأس امم افريقيا
[league_logo] => http://3.bp.blogspot.com/-4iampWUCLto/VmldL2XTz7I/AAAAAAAAD0I/eZFfzSxRbnE/s60/africa.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 1
[team1logo] => http://2.bp.blogspot.com/-mycTzHXuzJA/Ugbb-UG_3JI/AAAAAAAAEv0/_mzaSHnRedE/s60/egypt+(4).png
[team2logo] => http://1.bp.blogspot.com/-kYrkU4jahZY/UgbeVpHf8RI/AAAAAAAAFIQ/TBgM5fvVW14/s60/ghana+(3).png
[match_time] => 19:00
[channels_id] => Array
(
[0] => 18
)
[team1] => مصر
[team2] => غانا
)
[1] => Array
(
[match_id] => 2
[team1logo] => http://3.bp.blogspot.com/-_y1MazEn-vg/UgbeoIWUpII/AAAAAAAAFPI/JTRGGpG3GiQ/s60/mali+(4).png
[team2logo] => http://2.bp.blogspot.com/-GTxKONxvKy4/Ugt6AKXOmyI/AAAAAAAAF8Y/pPcM0O58cQI/s60/uganda_2.png
[match_time] => 19:00
[channels_id] => Array
(
[0] => 19
)
[team1] => مالي
[team2] => أوغندا
)
)
)
[1] => Array
(
[league_id] => 1
[league_name] => كأس ملك أسبانيا
[league_logo] => http://1.bp.blogspot.com/-zAzWT2Vpbe0/Vmle9TUWDlI/AAAAAAAAD04/-BKgPzRCT1k/s60/Copa_del_Rey_logo_since_2012.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 3
[team1logo] => http://4.bp.blogspot.com/-6sfdkbboNdk/VBxVKisRkcI/AAAAAAAADG8/oBKDHmBW5xc/s60/eibar+fc.png
[team2logo] => http://2.bp.blogspot.com/-S7p2yMaLywM/UhCz6GqNCRI/AAAAAAAAGFE/CfxzSQk8bgQ/s60/Atletco+Madrid2.Png
[match_time] => 18:15
[channels_id] => Array
(
[0] => 1
)
[team1] => إيبار
[team2] => أتلتيكو مدريد
)
[1] => Array
(
[match_id] => 4
[team1logo] => http://1.bp.blogspot.com/--6y77FXuPLI/UjeVcpJ-AJI/AAAAAAAAGok/QyZhwahPamo/s60/Celta+Vigo.png
[team2logo] => http://2.bp.blogspot.com/-tncIAL_U6mI/UgbnQw75V8I/AAAAAAAAFhA/8-9Xpw83GKY/s60/Real+Madrid+(3).png
[match_time] => 20:15
[channels_id] => Array
(
[0] => 3
)
[team1] => سيلتا فيغو
[team2] => ريال مدريد
)
)
)
[2] => Array
(
[league_id] => 2
[league_name] => كأس الرابطة الإنجليزية
[league_logo] => http://4.bp.blogspot.com/-31G65FeskFs/VmlezHMPm_I/AAAAAAAAD0w/9OMjh8AQP-M/s60/TheFA_CapitalOneCup.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 5
[team1logo] => http://3.bp.blogspot.com/-D0lb4b-qN5U/UgbeDosqjYI/AAAAAAAAFBY/Qg7kvoodvFY/s60/Liverpool+(2).png
[team2logo] => http://2.bp.blogspot.com/-prH3jgmfewQ/Ug8ZgNxPlcI/AAAAAAAAGAU/HLmbFvGuDB8/s60/Southampton.png
[match_time] => 20:00
[channels_id] => Array
(
[0] => 2
)
[team1] => ليفربول
[team2] => ساوثهامبتون
)
)
)
[3] => Array
(
[league_id] => 3
[league_name] => كاس ايطاليا
[league_logo] => http://2.bp.blogspot.com/-p9Kjb2_GZPU/VnAdQcHV9_I/AAAAAAAAD7E/6R-P54Upui4/s60/tim-cup.png
[league_matches] => Array
(
[0] => Array
(
[match_id] => 6
[team1logo] => http://1.bp.blogspot.com/-POxAfSSnlW0/UhCt7oQsdLI/AAAAAAAAGDo/rMRXx2mqvUI/s60/Juventus[1].Png
[team2logo] => http://3.bp.blogspot.com/-_Qj_GaxVaDE/UgaEPtt7EsI/AAAAAAAAEA8/redsOTj7F4Q/s60/Ac+Milan+(3).png
[match_time] => 20:00
[channels_id] => Array
(
[0] => 103
)
[team1] => يوفنتوس
[team2] => ميلان
)
)
)
)
)
And this is my PHP so far:
$str = file_get_contents($url);
$json = json_decode($str, true);
$date = $json['date'];
$leagues = $json['leagues'][0];
foreach ($leagues as $key => $value) {
for ($i=0; $i<count($value); $i++) {
foreach ($value[$i] as $key1 => $value1) {
$sql = "INSERT INTO table_name (column1,column2,column3,column4) VALUES (...,...,...,...)";
for ($c=0; $c<count($value1); $c++) {
foreach ($value1[$c] as $key2 => $value2) {
echo $value2;
}
}
}
}
}
the problem how can read all each array by foreach and store every value to table in database.
I would appreciate an example for this.

Basic structure to loop all nodes in your json
//leagues level
foreach ($json['leagues'] as $key => $league) {
$league_id = $league['league_id'];
//leagues -> league_matches level
foreach ($league['league_matches'] as $key => $match) {
$match_id = $match['match_id'];
//channel ids
foreach ($match['channels_id'] as $channels_id) {
//$channels_id;
//create an sql
$sql = "INSERT INTO xy (col1,col2,col3) values ($league_id,$match_id,$channels_id)";
$db->query($sql);
}
}
}
About the SQL You dont show any structure of your databse, so i cant help creating the sql.

I hope your JSON file sends the value using json_encode() method. You need to separate the array elements with a comma (,). Also you need to write the array indexes within quotes ('). Here is a corrected sample of your JSON page.
$retArr = Array
(
['date'] => 25-1-2017,
['leagues'] => Array
(
[0] => Array
(
['league_id'] => 0,
['league_name'] => كأس امم افريقيا,
['league_logo'] => http://3.bp.blogspot.com/-4iampWUCLto/VmldL2XTz7I/AAAAAAAAD0I/eZFfzSxRbnE/s60/africa.png,
['league_matches'] => Array
(
[0] => Array
(
['match_id'] => 1,
['team1logo'] => http://2.bp.blogspot.com/-mycTzHXuzJA/Ugbb-UG_3JI/AAAAAAAAEv0/_mzaSHnRedE/s60/egypt+(4).png,
['team2logo'] => http://1.bp.blogspot.com/-kYrkU4jahZY/UgbeVpHf8RI/AAAAAAAAFIQ/TBgM5fvVW14/s60/ghana+(3).png,
['match_time'] => 19:00
['channels_id'] => Array
(
[0] => 18
)
['team1'] => مصر ,
['team2'] => غانا
)
)
)
)
);
echo json_encode($retArr);
On the receiving page, you need to set a second parameter to TRUE in the json_decode() method so that you will get the result as an array rather than as a JSON Object.
$str = file_get_contents($url);
$json = json_decode($str, true);
$date = $json['date'];
$leagues = $json['leagues'][0];
foreach ($leagues as $key => $value) {
for ($i=0; $i<count($value); $i++) {
foreach ($value[$i] as $key1 => $value1) {
$sql = "INSERT INTO table_name (column1,column2,column3,column4) VALUES (...,...,...,...)";
for ($c=0; $c<count($value1); $c++) {
foreach ($value1[$c] as $key2 => $value2) {
echo $value2;
}
}
}
}
}
Try this way.

Related

PHP associative array- matched key value of each array will be a table row

I have an array like this-
Array
(
[sku] => Array
(
[0] => SKU125
[1] => SKU121
[2] => SKU122
[3] => SKU124
)
[variation_description] => Array
(
[0] => test another
[1] => test
[2] => test
[3] => test
)
[price_html] => Array
(
[0] => 400,200
[1] => 500
[2] => 600,300
[3] => 700
)
)
Is it possible to covert the array to like this table-
Any kind of help will be appreciated.
Thanks In Advance
As every key (sku , price_html etc) has same amount of data , so just push the corresponding key data to a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$re_structured = [];
foreach ($data as $each_key_data ) {
foreach ($each_key_data as $key => $value2 ) {
$re_structured[$key][] = $value2;
}
}
var_dump($re_structured);
You can simply iterate through data and create a new array.
$data = [
'sku' => ['SKU125', 'SKU121', 'SKU122', 'SKU124'],
'variation_description' => ['test another', 'test', 'test', 'test'],
'price_html' => ['400,200', '500', '600,300', '700']
];
$mapped = [];
$keys = array_keys($data);
$rows = count($data[reset($keys)]);
for ($i = 0; $i < $rows; $i++) {
$row = [];
foreach ($keys as $key)
$row[] = $data[$key][$i];
$mapped[] = $row;
}
This will result in
print_r($mapped);
Array
(
[0] => Array
(
[0] => SKU125
[1] => test another
[2] => 400,200
)
[1] => Array
(
[0] => SKU121
[1] => test
[2] => 500
)
[2] => Array
(
[0] => SKU122
[1] => test
[2] => 600,300
)
[3] => Array
(
[0] => SKU124
[1] => test
[2] => 700
)
)

Matching array value (PHP Array)

Input post :
$_POST['dateSlot']
$_POST['timeStart']
$_POST['timeEnd']
$_POST['quota']
These input post will resulting the below array.
Array
(
[dateSlot] => Array
(
[0] => 2018-04-05
[1] => 2018-04-05
[2] => 2018-04-05
)
[timeStart] => Array
(
[0] => 11:06 AM
[1] => 10:06 AM
[2] => 9:06 AM
)
[timeEnd] => Array
(
[0] => 11:06 AM
[1] => 9:06 AM
[2] => 7:06 AM
)
[quota] => Array
(
[0] => 12
[1] => 10
[2] => 10
)
)
I'm trying to foreach them to match the index key and form another array with this idea. Not so sure if can get the value I want :
foreach ($_POST['dateSlot'] as $k => $val) {
foreach ($_POST['timeStart'] as $k2 => $val2) {
foreach ($_POST['timeEnd'] as $k3 => $val3) {
foreach ($_POST['quota'] as $k4 => $val4) {
if($k == $k2 && $k == $k3 && $k == $k4){
$timeslots[$k]['date_slot'] = $val;
$timeslots[$k]['time_start'] = $val2;
$timeslots[$k]['time_end'] = $val3;
$timeslots[$k]['event_quota'] = $val4;
}
}
}
}
}
By that foreach, I'm getting the error Illegal string offset for date_slot, time_start, time_end, and event_quota
Based on the rows in the array, my goal is to re-form the array so that they all will be combined together to form 3 rows.
Example :
Array
(
[0] => Array
(
[date_slot] => 2018-04-05
[time_start] => 11:06 AM
[time_end] => 11:06 AM
[event_quota] => 12
)
[1] => Array
(
[date_slot] => 2018-04-05
[time_start] => 10:06 AM
[time_end] => 9:06 AM
[event_quota] => 10
)
[2] => Array
(
[date_slot] => 2018-04-05
[time_start] => 9:06 AM
[time_end] => 7:06 AM
[event_quota] => 10
)
)
Another approach to grouping this kind of data without needing to know the key names in advance.
This works by using the first row's data current( $data ) as the main iterator, then builds an array by combining the outer keys array_keys( $data ) and the inner column value array_column( $data, $column ) with array_combine() which combines two arrays of keys and an array of value to make each row's final array structure keyed by column name.
This is absolutely reliant on each multidimensional array having the same count of elements. As such this is not suitable for forms with checkbox inputs in them. At which point I would suggest using name="row[0][ColumnName]" as your name attribute and negating the need for this array processing.
http://php.net/manual/en/function.array-column.php
http://php.net/manual/en/function.array-combine.php
http://php.net/manual/en/function.array-keys.php
$data = array(
'Column-1'=>array('Row-1a','Row-2a','Row-3a'),
'Column-2'=>array('Row-1b','Row-2b','Row-3b'),
'Column-3'=>array('Row-1c','Row-2c','Row-3c')
);
$array = array();
foreach( array_keys( current( $data ) ) as $column )
{
$array[] = array_combine( array_keys( $data ), array_column( $data, $column ) );
}
print_r( $array );
Produces
Array
(
[0] => Array
(
[Column-1] => Row-1a
[Column-2] => Row-1b
[Column-3] => Row-1c
)
[1] => Array
(
[Column-1] => Row-2a
[Column-2] => Row-2b
[Column-3] => Row-2c
)
[2] => Array
(
[Column-1] => Row-3a
[Column-2] => Row-3b
[Column-3] => Row-3c
)
)
If you know that the element keys in all 4 of those post variables will always correlate to one timeslot element, then I think this will work for you:
foreach ($_POST['dateSlot'] as $key => $value) {
$timeslots[$key] = [
'date_slot' => $_POST['dateSlot'][$key],
'time_start' => $_POST['timeStart'][$key],
'time_end' => $_POST['timeEnd'][$key],
'event_quota' => $_POST['quota'][$key],
];
}
print_r($timeslots);
$dateSlot = $_POST['dateSlot']
$timeStart = $_POST['timeStart']
$timeEnd = $_POST['timeEnd']
$quota = $_POST['quota']
$all = array();
foreach($dateSlot as $key => $date) {
$all[] = array(
"data_slot" => $dateSlot[$key],
"time_start" => $timeStart[$key],
"time_end" => $timeEnd[$key],
"quota" => $quota[$key]
)
}
Input
$array = array(
'dateSlot' => array('2018-04-05','2018-04-05','2018-04-05'),
'timeStart' => array('11:06 AM','10:06 AM','9:06 AM'),
'timeEnd' => array('11:06 AM','9:06 AM','7:06 AM'),
'quota' => array(12,10,10)
);
Solution
$new = array();
for($i=0;$i<count($array['dateSlot']);$i++){
$new[] = array(
'dateSlot' => $array['dateSlot'][$i],
'timeStart' => $array['timeStart'][$i],
'timeEnd' => $array['timeEnd'][$i],
'event_quota' => $array['quota'][$i],
);
}
echo "<pre>";print_r($new);
Output
Array
(
[0] => Array
(
[dateSlot] => 2018-04-05
[timeStart] => 11:06 AM
[timeEnd] => 11:06 AM
[event_quota] => 12
)
[1] => Array
(
[dateSlot] => 2018-04-05
[timeStart] => 10:06 AM
[timeEnd] => 9:06 AM
[event_quota] => 10
)
[2] => Array
(
[dateSlot] => 2018-04-05
[timeStart] => 9:06 AM
[timeEnd] => 7:06 AM
[event_quota] => 10
)
)

Bulid for loop based on given array

I am generating dynamic textbox for save and add more functionality and i have to store that data in database i got the array but i dont know how to put that array in to loop so i can get my data.
Array looks like this based on this prepare loop so i can access every element of array:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a1
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
[1] => Array
(
[0] => Array
(
[0] => Array
(
[prem_type] => 1
)
[1] => Array
(
[phase_name] => a2
)
[2] => Array
(
[counter] => 2
)
[3] => Array
(
[block] => A
)
[4] => Array
(
[block] => B
)
)
)
)
Thanks
try this
$array = //your array
foreach($array as $value){
foreach($value as $value2){
foreach($value2 as $value3){
foreach($value3 as $key3 => $value3){
//$key3 is rem_type, phase_name…
//$value3 is required values
}
}
}
}
To get to the data you can use something like:
foreach ($array AS $row) {
$prem_type = $row[0][0]['prem_type'];
$phase_name = $row[0][1]['phase_name'];
$counter = $row[0][2]['counter'];
$block1 = $row[0][3]['block'];
$block2 = $row[0][4]['block'];
}
An alternative is to restructure the array into something more tidy:
$result = array();
foreach ($array AS $rowId => $row) {
$result[$rowId] = array(
'prem_type' => $row[0][0]['prem_type'],
'phase_name' => $row[0][1]['phase_name'],
'counter' => $row[0][2]['counter'],
'block1' => $row[0][3]['block'],
'block2' => $row[0][4]['block']
);
}
This results in:
Array
(
[0] => Array
(
[prem_type] => 1,
[phase_name] => a1,
[counter] => 2,
[block1] => A,
[block2] => B
)
...
)
Here is the answer:
for($i=0;$i<count($data1);$i++){
for($j=0;$j<count($data1[$i]);$j++){
$prem_type =$data1[$i][$j][0]['prem_type'];
$prem_name= $data1[$i][$j][1]['phase_name'];
$no_of_phase= $data1[$i][$j][2]['counter'];
echo $prem_type." ".$prem_name." ".$no_of_phase."<br>";
for($k=3;$k<count($data1[$i][$j]);$k++){
echo $data1[$i][$j][$k]['unitname']."<br>";
}
}
}

PHP fetch 3d array

I have below array and i want to fetch [2] => Array with foreach but it's showing me an error.
for example array name is $other
Array
(
[0] => Array
(
[0] => aaaaaaaaaaaa
[1] => bbbbbbbbbbbb
[2] => cccccccccccc
)
[1] => Array
(
[0] => dddddddddddd
[1] => eeeeeeeeeeee
[2] => ffffffffffff
)
[2] => Array
(
[0] => gggggggggggg
[1] => hhhhhhhhhhhh
[2] => iiiiiiiiiiii
)
)
fetch array:
foreach ($other[2] as $value) {
echo $value.'<br/>';
}
How do I print all the values of the second array?
You need to nest further more
foreach ($other as $arr)
{
foreach($arr as $k=>$v)
{
if($k==2)
{
echo $v.'<br/>';
}
}
}
OUTPUT :
cccccccccccc
ffffffffffff
iiiiiiiiiiii
Try Something like this,
<?php
$x = array
(
0 => array
(
0 => 'aaaaaaaaaaaa',
1 => 'bbbbbbbbbbbb',
2 => 'cccccccccccc'
),
1 => array
(
0 => 'dddddddddddd',
1 => 'eeeeeeeeeeee',
2 => 'ffffffffffff'
),
2 => array
(
0 => 'gggggggggggg',
1 => 'hhhhhhhhhhhh',
2 => 'iiiiiiiiiiii'
)
);
$count = count($x);
$w = $count - 1;
var_dump($x[$w]);
?>

how can i count an element if it appears more than once in the same array?

how can i count an element if it appears more than once in the same array?
I already tried with array_count_values, but it did not work, is it beacuse i got more than one key and value in my array?
This is my output from my array (restlist)
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla)
[1] => Array ( [restaurant_id] => 32144 [title] => test5)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
[3] => Array ( [restaurant_id] => 32144 [title] => test5)
[4] => Array ( [restaurant_id] => 42154 [title] => blabla2 )
)
I want it to count how many times the same element appears in my array and then add the counted value to my newly created 'key' called hits in the same array.
Array (
[0] => Array ( [restaurant_id] => 47523 [title] => cafe blabla [hits] => 1)
[1] => Array ( [restaurant_id] => 32144 [title] => test5 [hits] => 2)
[2] => Array ( [restaurant_id] => 42154 [title] => blabla2 [hits] => 2)
)
This is how i tried to do what i wanted.
foreach ($cooltransactions as $key)
{
$tempArrayOverRestaurants[]= $key['restaurant_id'];
}
$wordsRestaruants = array_count_values($tempArrayOverRestaurants);
arsort($wordsRestaruants);
foreach ($wordsRestaruants as $key1 => $value1)
{
$temprestaurantswithhits[] = array(
'restaurant_id' => $key1,
'hits' => $value1);
}
foreach ($restlistas $key)
{
foreach ($temprestaurantswithhits as $key1)
{
if($key['restaurant_id'] === $key1['restaurant_id'])
{
$nyspisestedsliste[] = array(
'restaurant_id' => $key['restaurant_id'],
'title' => $key['title'],
'hits' => $key1['hits']);
}
}
}
I know this is probably a noob way to do what i want but i am still new at php..I hope you can help
Just try with associative array:
$input = array( /* your input data*/ );
$output = array();
foreach ( $input as $item ) {
$id = $item['restaurant_id'];
if ( !isset($output[$id]) ) {
$output[$id] = $item;
$output[$id]['hits'] = 1;
} else {
$output[$id]['hits']++;
}
}
And if you want to reset keys, do:
$outputWithoutKeys = array_values($output);

Categories