Datastream Array Returning Only First Value - php

I am using the MODX cms to output data from a third party, and I am stumped on how to return a nested array, currently I am only getting it to return the first array or NULL. Here is a sample of the code I am using:
$datastream = '[{"id":57,
"offer_info":{"offer_headline":"Main Offer Headline",
"published_title":"Displayed Main Title"},
// My issue is here with the nested array
"service_categories":[{"service_category_code":"D",
"headline":"My Headline for D",
"midline":"Middle copy",
"footline":"Footer copy for D"},
{"service_category_code":"T",
"headline":"My Headline for T",
"image":"image.svg",
"footline":"Footer copy for T"}]}]';
$output_json = json_decode($datastream);
$output_json = json_decode($datastream, true); // this returns null for everything
foreach($output_json as $component) {
$productid = $component->id; // this returns ok
$offer_headline = $component->offer_info->offer_headline; // this returns ok
$published_title = $component->offer_info->published_title; // this returns ok
$service_categories_category_code = $component->service_categories[0]->service_category_code; // this only returns first value
$service_categories_category_code = $component->service_categories->service_category_code; // this returns NULL
var_dump($service_categories_category_code);
I am able to take the values that return ok and place them in my code, but the nested array is only returning the first value, and I'm not sure if I am doing this correctly:
if ($service_categories_category_code = "D") {
$d_details_headline = $component->service_categories[0]->headline;
$d_details_midline = $component->service_categories[0]->midline;
$d_footline = $component->service_categories[0]->footline;
} elseif ($service_categories_category_code = "T") {
$t_details_headline = $component->service_categories[0]->headline;
$t_details_image = $component->service_categories[0]->image;
$t_details_footline = $component->service_categories[0]->footline;
};
Thank you very much in advance for any help

Hope this helps You :
<?php
$datastream = '[{"id":57,"offer_info":{"offer_headline":"Main Offer
Headline","published_title":"Displayed Main
Title"},"service_categories":[{"service_category_code":"D",
"headline":"My Headline for D","midline":"Middle
copy","footline":"Footer copy for D"},{"service_category_code":"T",
"headline":"My Headline for T",
"image":"image.svg",
"footline":"Footer copy for T"}]}]';
$output_json = json_decode($datastream);
//$output_json = json_decode($datastream, true); // this returns null for everything
$data = array();
foreach($output_json as $component) {
$productid = $component->id; // this returns ok
$offer_headline = $component->offer_info->offer_headline; // this returns ok
$published_title = $component->offer_info->published_title; // this returns ok
$data['productid'] = $component->id;
$data['offer_info']['offer_headline'] = $component->offer_info->offer_headline;
$data['offer_info']['published_title'] = $component->offer_info->published_title;
foreach ($component->service_categories as $comp) {
if ($comp->service_category_code == 'D') {
$data['D']['service_category_code'] = $comp->service_category_code;
$data['D']['headline'] = $comp->headline;
$data['D']['midline'] = $comp->midline;
$data['D']['footline'] = $comp->footline;
} elseif ($comp->service_category_code == 'T') {
$data['T']['service_category_code'] = $comp->service_category_code;
$data['T']['headline'] = $comp->headline;
$data['T']['image'] = $comp->headline;
$data['T']['footline'] = $comp->footline;
}
}
print_r($data);
}

Related

Why do I get an array in response after calling an array value by key

I call a function, and I want to get a response with an array and two elements per key.
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/_giveRandomQuestSearchPok.php');
$pokQ = QuestPoks::giveRandomQuestPok();
The function itself looks like this
public static function giveRandomQuestPok() {
$sC = \Work::$sql->prepare('SELECT region FROM users WHERE id = ?');
$sC->bind_param("i", $_SESSION['id']);
$sC->execute();
$dA = $sC->get_result();
$region = $dA->fetch_assoc();
if($region['region'] == 1){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Kanto.php');
}elseif($region['region'] == 3){
include_once($_SERVER['DOCUMENT_ROOT'].'/matsuka/randomPoks/Hoenn.php');
}
$rarity = mt_rand(1,100);
if($rarity == 1){
$rare = 1;
$object = \matsuka\Rare[mt_rand(0, count(\matsuka\Rare) - 1)];
}elseif($rarity > 1 && $rarity <= 33){
$rare = 2;
$object = \matsuka\Uncommon[mt_rand(0, count(\matsuka\Uncommon) - 1)];
}else{
$rare = 3;
$object = \matsuka\Common[mt_rand(0, count(\matsuka\Common) - 1)];
}
$array = array();
$array['pok'] = $object;
$array['rare'] = $rare;
return $array;
}
After executing the function I want to assign two variables to control the result
$pok = $pokQ["pok"];
$rare = $pokQ["rare"];
But the handler still reads them as an array.
And when I paste it into sql I get an Array, although I was hoping to get the array data by their corresponding key.
In var_dump I get quite a strange answer. I seem to see the required value of array called by the key, but on top of that I see another array, if I understand correctly.
int(401)
{
"name":"\u0413\u0443\u0441\u0442\u0430\u0432",
"actionQuest":"<img src=\"\/img\/quests\/7.webp\" class=\"quest\"> \u041e\u0431\u043d\u043e\u0432\u043b\u0435\u043d\u0430 \u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u044f \u0432 \u0437\u0430\u0434\u0430\u043d\u0438\u0438 \u00ab\u041f\u043e\u043c\u043e\u0449\u044c \u0441\u0442\u0430\u0440\u043e\u043c\u0443 \u043f\u0440\u0438\u044f\u0442\u0435\u043b\u044e\u00bb. \u0417\u0430\u0433\u043b\u044f\u043d\u0438\u0442\u0435 \u0432 \u0410\u043a\u0432\u0430\u0431\u0443\u043a.",
"question":"\u0422\u044b \u043e\u0442\u043b\u0438\u0447\u043d\u043e \u0441\u043f\u0440\u0430\u0432\u0438\u043b\u0441\u044f \u0441 \u043c\u043e\u0438\u043c \u043f\u0440\u043e\u0448\u043b\u044b\u043c \u0437\u0430\u0434\u0430\u043d\u0438\u0435\u043c. \u042f \u0445\u043e\u0440\u043e\u0448\u0435\u043d\u044c\u043a\u043e \u0438\u0437\u0443\u0447\u0438\u043b \u0442\u043e\u0433\u043e \u043f\u043e\u043a\u0435\u043c\u043e\u043d\u0430. \u0422\u0435\u043f\u0435\u0440\u044c \u043c\u043d\u0435 \u043d\u0443\u0436\u0435\u043d: <div class=\"questPokemon\"><img src=\"\/img\/pokemons\/mini\/normal\/Array.webp\"> <div>#Array <\/div><\/div>"
}
Why does this happen and what is my mistake?
In the array I should only get 3-digit numbers under each key

PHP add unique User array to newly created array while iterating over Episode authors object

Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

getting error to display all record in php json

I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work

Minimize efforts with foreach

I'm trying to build a script that will download users from a db table and attach a new random IP to each user based on his state.
The problem is that I wrote a lot of code and there is still much Copy/Paste job to be done if I keep it with this approach.
Can someone point me to the right direction on how to properly do that?
So first I have 50 of these:
$California_Text = file_get_contents('state/California.txt');
$California_textArray = explode("\n", $California_Text);
$Idaho_Text = file_get_contents('state/Idaho.txt');
$Idaho_textArray = explode("\n", $Idaho_Text);
$Illinois_Text = file_get_contents('state/Illinois.txt');
$Illinois_textArray = explode("\n", $Illinois_Text);
$Indiana_Text = file_get_contents('state/Illinois.txt');
$Indiana_textArray = explode("\n", $Indiana_Text);
$Iowa_Text = file_get_contents('state/Iowa.txt');
Then I have 50 of these:
while($row = $result->fetch_assoc()) {
if (isset($row["state"])) {
foreach ($row as $value){
$California_randArrayIndexNum = array_rand($California_textArray);
$p_California = $California_textArray[$California_randArrayIndexNum];
$Texas_randArrayIndexNum = array_rand($Texas_textArray);
$p_Texas = $Texas_textArray[$Texas_randArrayIndexNum];
$Alabama_randArrayIndexNum = array_rand($Alabama_textArray);
$p_Alabama = $Alabama_textArray[$Alabama_randArrayIndexNum];
$Alaska_randArrayIndexNum = array_rand($Alaska_textArray);
$p_Alaska = $Texas_textArray[$Alaska_randArrayIndexNum];
$Arizona_randArrayIndexNum = array_rand($Arizona_textArray);
$p_Arizona = $California_textArray[$Arizona_randArrayIndexNum];
.....
Then I have 50 of these:
if ($row["state"] == "california") {
$stateip = $p_California;
}
else if ($row["state"] == "texas") {
$stateip = $p_Texas;
}
else if ($row["state"] == "alabama") {
$stateip = $p_Alabama;
}
else if ($row["state"] == "alaska") {
$stateip = $p_Alaska;
}
I'm pretty much sure that it's a bad approach.. Maybe there's a way to do all this with like 3 lines of foreach?
Something like this:
// holds your content
$state_content = [];
while($row = $result->fetch_assoc()) {
// check do we have state set
if (!empty($row["state"])) {
$stateip = getStateIpByName($row["state"]);
}
}
/**
* Returns random IP
*/
function getStateIpByName($state_name) {
$content = getStateContent($state_name);
return $content[array_rand($content)];
}
/**
* Returns your's state content by state name
*/
function getStateContent($state_name) {
// checks do we already have content for this state
if(!isset($state_content[$state_name])) {
// generate file name
$file_name = "state/";
$file_name .= str_replace(" ", "", ucwords($state_name));
$file_name .= ".txt";
$state_text = file_get_contents($file_name);
$state_content[$state_name] = explode("\n", $state_text);
}
return $state_content[$state_name];
}
There are probably some errors but you will get idea.
Store all states in an array and do all operations within a foreach block
$states=['california',..];
foreach($states as $state){
//Your code for one state
//Replace state name with $state variable
}

Categories