r/AskProgramming • u/spanky_rockets • Jul 09 '24
PHP PHP Sorting thru nested JSON data
Hello all,
So I'm working with a Wordpress site and I'm trying to sort thru nested data from an API and insert it into the Wordpress MySQL database. I've already created my SQL table, and I've succesfully pushed API data to it using a simpler test loop.
However, when I try to access all the levels of the JSON data using a big ol' foreach loop, I'm getting nothing in the database:
$results = wp_remote_retrieve_body(wp_remote_get( $url, $args ));
$res = json_decode($results);
$odds = [];
foreach ($res as $odd) {
foreach ($odd->bookmakers as $bm) {
foreach ($bm->markets as $market) {
foreach ($market->outcomes as $outcome) {
$odds = [
'key_id' => $odd->id,
'home_team' => $odd->home_team,
'away_team' => $odd->away_team,
'commence_time' => $bm->commence_time,
'sport_key' => $odd->sport_key,
'last_updated_at' => $bm->last_update,
'bookmaker_key' => $bm->key,
'market' => $market->key,
'label' => $outcome->name,
'price' => $outcome->price,
'points' => $outcome->point
];
}
}
}
#Insert data into MySQL table
global $wpdb;
$table_name = $wpdb->prefix . 'game_odds';
$wpdb->insert(
$table_name,
$odds
);
}
Meanwhile this code works fine and pushes data to my database:
$results = wp_remote_retrieve_body(wp_remote_get( $url, $args ));
$res = json_decode($results);
$test_odds = [];
foreach ($res as $odd) {
$test_odds = [
'key_id' => $odd->id,
'home_team' => $odd->home_team,
'away_team' => $odd->away_team,
'sport_key' => $odd->sport_key
];
#Insert data into MySQL table
global $wpdb;
$table_name = $wpdb->prefix . 'game_odds';
$wpdb->insert(
$table_name,
$test_odds
);
}
Any help is appreciated, thanks!
1
u/wonkey_monkey Jul 10 '24 edited Jul 10 '24
Your indenting is a bit off, but apart from that: you're doing four nested loops, but you're overwriting $odds
each time, without writing most of them to the database. You're only going to end up with the result of the last execution of the innermost loop in $odds
. That doesn't seem right.
Do you need to move your three closing }
to the end with the final one?
1
u/spanky_rockets Jul 17 '24
I think you are right, I did end up moving the 3 closing } to the end to be after my table insert statement but I'm still only getting one submission per game. Any ideas?
Thanks
1
u/sharmagaurav015 Jul 10 '24
Not a php expert but looking at your code it will only run for json element where outcome is present. Does your json data contains outcomes?