Get array data from JSON - php

My target is to make an array of Objets(Article), I manage to recuperate the pmid, doi and title but when it comes to the array location, I couldn't do it, this the code I have tried:
<?php
class Article
{
private $pmid;
private $doi;
private $title;
private $location=array();
public function setLocations($tabLocations){
foreach ($tabLocations as $key => $value) {
$location[]=$value;
}
}
public function setPmid($_pmid){
$this->pmid=$_pmid;
}
public function setDoi($_doi){
$this->doi=$_doi;
}
public function setTitle($_title){
$this->title=$_title;
}
//getters
public function getTitle(){
return $this->title;
}
}
//get pmid from DOM
require_once "simple_html_dom.php";
$html=new simple_html_dom();
$html->load_file('http://brainspell.org/search?query=psen+1');
$pmid=array();
foreach ($html->find('.paper-stuff') as $article) {
$pmid[]= str_replace("/article/","",$article->find('a',0)->getAttribute('href'));
}
//Create ALLArticles TAb
$articlesTab=array();
//upload data file
$json=file_get_contents("C:\wamp\www\projet1\json\allArticles.json");
$data=json_decode($json,true);
foreach ($pmid as $tabPmid) {
foreach ($data as $key=>$value) {
if($value["pmid"]==$tabPmid)
{
$details=new Article();
$details->setPmid($value["pmid"]);
$details->setDoi($value["doi"]);
$details->setTitle($value["title"]);
$details->setLocations($value['experiment']['location']);
$articlesTab[]=$details;
}
}
}
?>
This a portion of my JSON code:
{
"papers": {
"paper": [
{
"pmid": "6330179",
"doi": "10.1002/cne.902260203",
"experiment": [
{
"id": "12789",
"location": [
"-46.0,-80.0,2.0",
"-42.0,-76.0,-2.0",
"44.0,-72.0,-2.0",
"52.0,-68.0,-6.0",
"-32.0,-88.0,4.0",
"-32.0,-90.0,8.0",
"34.0,-82.0,8.0",
"34.0,-78.0,8.0",
"-30.0,-52.0,-12.0",
"-30.0,-52.0,-10.0",
"28.0,-66.0,-16.0",
"26.0,-66.0,-12.0",
"-46.0,-76.0,6.0",
"-46.0,-78.0,0.0",
"46.0,-70.0,4.0",
"48.0,-74.0,0.0"
]
}
]
},
{
"pmid": "10022492",
"doi": "10.1093/cercor/9.1.20",
"experiment": [
{
"id": "258",
"location": [
"-42.0,26.0,20.0",
"-36.0,30.0,16.0",
"-30.0,32.0,0.0",
"-28.0,14.0,48.0",
"-20.0,8.0,56.0",
"-32.0,4.0,52.0",
"50.0,10.0,36.0",
"48.0,24.0,20.0",
"32.0,0.0,56.0",
"8.0,-2.0,64.0",
"4.0,-8.0,68.0",
"-16.0,-4.0,12.0",
"-2.0,-18.0,12.0",
"-8.0,2.0,8.0",
"-44.0,-28.0,32.0",
"-4.0,-60.0,60.0",
"36.0,-58.0,52.0"
]
},
If there is anyone that could help me.Thanks in advance :D

If you notice location is another array so for you to get all its elements, it needs to be imploded. so try something like this .
$details->setLocations(implode(",",$value['experiment']['location']));
This will print the array as a string separated by comma ,; maybe you can choose what you want as the separator.

You simply missed $this to reference your object property in setLocations
public function setLocations($tabLocations){
foreach ($tabLocations as $key => $value) {
$this->location[]=$value; // $this->location is where you want to store your locations
}
}
and by the way, I don't see any need to iterate over $tabLocations in your setter. Wouldn't
public function setLocations($tabLocations){
$this->locations = $tabLocations;
}
do the trick too?
Or if you want to get rid of the keys:
public function setLocations($tabLocations){
$this->locations = array_values($tabLocations);
}

Related

How to show array in Json with Fractal?

I want to save REST API data with array to database, its work, all value save to the table, but i still get error when i want to view the result in json.
Here is my error
"message": "Argument 1 passed to App\\Transformers\\NewLoanOfferTransformer::transform() must be an instance of App\\Model\\AntiAttrition, array given, called in /home/insko23/testing.insko.my/vendor/league/fractal/src/Scope.php on line 338",
My Controller
public function new_loan_offer(Request $request, AntiAttrition $antiattrition)
{
$new = array_map(null, $request->mo_id, $request->id_clrt,$request->TaskID,$request->ACID,$request->CustIDNo);
foreach($new as $new) {
$request = new AntiAttrition;
$request->mo_id = $new[0];
$request->id_clrt = $new[1];
$request->TaskID = $new[2];
$request->ACID = $new[3];
$request->CustIDNo = $new[4];
$request->save();
}
$response = fractal()
->item($new)
->transformWith(new NewLoanOfferTransformer)
->toArray();
return response()->json($response,201);
}
My App\Transformer
<?php
namespace App\Transformers;
use App\Model\AntiAttrition;
use App\Model\SettlementInfo;
use League\Fractal\TransformerAbstract;
class NewLoanOfferTransformer extends TransformerAbstract
{
public function transform (AntiAttrition $antiattrition)
{
return[
'id' => $antiattrition->id,
'mo_id'=> $antiattrition->mo_id,
'assign_by'=> $antiattrition->assigned_by,
'id_clrt' => $antiattrition->id_clrt,
'TaskID'=> $antiattrition->TaskID,
'ACID'=> $antiattrition->ACID,
'CustIDNo'=> $antiattrition->CustIDNo
];
}
}
I want to show the result in json, like below
{
"data": [
{
"mo_id": "123",
"id_clrt": "10000000049",
"ACID": "123",
.....
},
{
"mo_id": "1234",
"id_clrt": "10000000045",
"ACID": "1235",
.....
},
{
"mo_id": "124",
"id_clrt": "10000000044",
"ACID": "1245",
.....
},
],
}
Please help me to solve this problem
In the foreach loop, avoid using same name for array and elements of the array you are iterating over, you can rename foreach($new as $new) to foreach($newArray as $new), or something meaningful with your code logic. Also rather than using $new[0] use $new['mo_id'] for referring to the key of the array

PHP/Laravel: How to insert a new json field when creating JSON in PHP?

I am returning JSON to my frontend like this:
public function newFlavorOrders()
{
$orders = request()->user()->ordersPaid;
return response()->json(['flavor_orders' => $orders]);
}
and right now, that returns this to the frontend:
{ orders: [
{
color: "Green"
size: "Large",
order_products: [ {'itemNum': 3, 'imgUrl': "zera.jpg"}, {'itemNum': 5, 'imgUrl': "murto.jpg"} ]
},
{
color: "Blue"
size: "Large",
order_products: [ {'itemNum': 3, 'imgUrl': "mcue.jpg"}, {'itemNum': 5, 'imgUrl': "cloa.jpg"} ]
}
]
}
But I want to alter the controller PHP function to add a field to each order_products item. I have the imgURL, but I want to add a processedImgUrl and stub it with true right now. How can I add the field to the above php function when returning the JSON?
Without the dataset this may not be exactly accurate but the way to do this is either to perform an array push or do a foreach loop and add create the index to be appended.
For example:
public function newFlavorOrders()
{
// CREATE A NEW ARRAY TO ADD THE MODIFIED DATA TO
$modified = array();
$orders = request()->user()->ordersPaid;
// LOOP THROUGH AND ADD THE VALUE TO THE ITERATION
foreach($orders as $row) {
foreach($row['order_products'] as $val){
$modified = $val;
if(!empty($val['imgUrl'])){
$modified['processedImgUrl'] = TRUE;
} else {
$modified['processedImgUrl'] = FALSE;
}
}
}
return response()->json(['flavor_orders' => $modified]);
}
Something like this should work. You need to loop through the first array, then get down to the next level array (order_products).
public function newFlavorOrders()
{
$orders = request()->user()->ordersPaid;
$orders = $orders->map(function ($order) {
$order->order_products = $order->order_products->map(function ($products) {
$products['processedImgUrl'] = true;
return $products;
});
return $order;
});
return response()->json(['flavor_orders' => $orders]);
}

Integrating mailchimp with CRM

Need to get campaign_id with the list_id that I've got. My goal is to get all the campaign data and then sort out using the list_id. I have been able to retrieve the campaign response body, but somehow failing to get the campaign list_id. Any help or a different approach would be appreciated. Sharing my code and mailchimp api related reference.
MailChimp api ref:
"campaigns": [
{
"id": "42694e9e57",
"type": "regular",
"create_time": "2015-09-15T14:40:36+00:00",
"archive_url": "http://",
"status": "save",
"emails_sent": 0,
"send_time": "",
"content_type": "template",
"recipients": {
"list_id": "57afe96172", // this is required
"segment_text": ""
},
My Progress:
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns"); // gives a response consisting 3 rows, required value is in 1st row, which is an array
foreach ($MCcampaigninfo as $key => $value) {
if ($value[8]->'list_id' == $list_id) { //under the 'campaign'array, we need the 9th position property 'recipient'
$campaign_id = $value[12]->'id';
}
}
}
This code assumes the response of $mc_api->get is equal to the JSON you showed in your example
public static function getCampaignID($list_id) {
$campaigns = json_encode(self::$mc_api->get("/campaigns"), true);
$campaignIds = [];
foreach ($campaigns as $campaign) {
//if the list_id matches the current campaign recipients['list_id'] add to the array
if ($campaign['recipients']['list_id'] === $list_id) {
$campaignIds[] = $campaign['id'];
}
}
//return an array with campaignIds
return $campaignIds;
}
Got it working. The api structure seems different in reality from their documentation. Thanks for all the help. Posting my updated code.
public static function getCampaignID($list_id){
$MCcampaigninfo = self::$mc_api->get("/campaigns");
foreach ($MCcampaigninfo as $key => $campaign) {
if($key == campaigns){
foreach ($campaign as $key2 => $clist) {
foreach ($clist as $key3 => $recip) {
if($key3 == id){
$campaign_id = $recip;
}
elseif($key3 == recipients){
foreach($recip as $key4 => $listid){
if($key4 == list_id){
if($listid == $list_id){
return $campaign_id;
}
}
}
}
}
}
}
}
}

php | dynamic api call

I am trying to create a dynamic endpoint for a API I am creating in order to include some data but only if it is required so I can use it in multiple places.
The idea is to have api.domain.com/vehicle to bring back basic vehicle information but if I did api.domain.com/vehicle?with=owners,history then the idea is to have a function which maps the owners and history to a class which will return data but only if it is required.
This is what I currently have.
public static function vehicle()
{
$with = isset($_GET['with']) ? $_GET['with'] : null;
$properties = explode(',', $with);
$result = ['vehicle' => Vehicle::data($id)];
foreach ($properties as $property) {
array_push($result, static::getPropertyResponse($property));
}
echo json_encode($result);
}
Which will then call this function.
protected static function getPropertyResponse($property)
{
$propertyMap = [
'owners' => Vehicle::owner($id),
'history' => Vehicle::history($id)
];
if (array_key_exists($property, $propertyMap)) {
return $propertyMap[$property];
}
return null;
}
However, the response I'm getting is being nested within a index, which I don't want it to be. The format I want is...
{
"vehicle": {
"make": "vehicle make"
},
"owners": {
"name": "owner name"
},
"history": {
"year": "26/01/2018"
}
}
But the format I am getting is this...
{
"vehicle": {
"make": "vehicle make"
},
"0": {
"owners": {
"name": "owner name"
}
},
"1": {
"history": {
"year": "26/01/2018"
}
}
}
How would I do this so it doesn't return with the index?
Vehicle::history($id) seems to return ['history'=>['year' => '26/01/2018']], ...etc.
foreach ($properties as $property) {
$out = static::getPropertyResponse($property) ;
$result[$property] = $out[$property] ;
}
Or your methods should returns something like ['year' => '26/01/2018'] and use :
foreach ($properties as $property) {
$result[$property] = static::getPropertyResponse($property) ;
}

PHP foreach array IDs

I have a foreach loop that is supposed to loop through JSON and return the appropriate ID of each video listed in JSON using the Youtube api.
Here is my code:
class Videos {
private $mVideoUrl;
function setVideoTitle($videoUrl){
$this->mVideoUrl= $videoUrl;
}
function getVideoTitle(){
return $this->mVideoUrl;
}
}
$jsonFile = file_get_contents($url);
$jfo = json_decode($jsonFile);
$items = $jfo->items;
$vidArray = array();
foreach ($items as $item){
if(!empty($item->id->videoId)){
$Videos = new Videos;
$Videos->setVideoUrl($item->id->videoId);
$id = $Videos->getVideoUrl();
array_push($vidArray, $id);
}
echo $vidArray[0];
}
Problem is, the array push is working correctly, but it is only adding the 1st ID in the list only for each loop iteration when i echo it. When I echo the $id variable, it prints all IDs just fine.
Ultimately i want to be able to create an object for each video, storing it's ID and other information.
I feel like this is a simple fix but i can't figure it out for the life of me.
I would appreciate any help!
Also if i am going about this all wrong, advice is appreciated as well!
Thanks!
I've played little bit with your code. I've modified your class. I've renamed plurar Videos to Video (singular).
Then I've added an attribute $id, because name of properties should be simple and represent the data we want to store in them.
Then I've added getter and setter for the $id property.
I don't know the $url, so I've just write simple JSON string instead. I tried to mimic the structure that you're using in your code.
Then I've added () to the end of new Video() to have proper constructor called.
And instead of pushing elements into array, I'm using proper $array[$index] = assignment.
Last thing, I've moved writing out the data out of the foreach-cycle. And I'm using var_export to get proper php code to play with if redirected to another file.
<?php
class Video
{
private $mVideoUrl;
private $id; // added id attribute
/**
* #return mixed
*/
public function getId() // added getter
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id) // added setter
{
$this->id = $id;
}
function setVideoTitle($videoUrl)
{
$this->mVideoUrl = $videoUrl;
}
function getVideoTitle()
{
return $this->mVideoUrl;
}
}
// ignored for now
// $jsonFile = file_get_contents($url);
$jsonFile = '{"items": [
{ "id": { "videoId": 1, "url": "http://www.youtube.com/1" } },
{ "id": { "videoId": 2, "url": "http://www.youtube.com/2" } },
{ "id": { "videoId": 3, "url": "http://www.youtube.com/3" } },
{ "id": { "videoId": 4, "url": "http://www.youtube.com/4" } },
{ "id": { "videoId": 5, "url": "http://www.youtube.com/5" } }
]
}';
$jfo = json_decode($jsonFile);
$items = $jfo->items;
$vidArray = array();
foreach ($items as $item)
{
if (!empty($item->id->videoId))
{
$Video = new Video(); // added brackets
$Video->setId($item->id->videoId); // changed to setId
$Video->setVideoTitle($item->id->url);
$id = $Video->getId();
$vidArray[$id] = $Video;
}
}
// write out all data
var_export($vidArray);
In your code your class Videos contains two functions
setVideoTitle(...),
getVideoTitle()
but in your foreach you have called $videos->getVideoUrl() , $videos->setVideoUrl(...)
what is this ???

Categories