Whole php array into variable... Or something similar - php

First time Ive posted on here..
So Im new to php, mysql and JSON, and Im having some issues, I may just be approaching the problem in the incorrect way, so let me know what you think.
Basically there's a website that I'm trying to do that has some info located on another server, I fetch that info with JSON.
Here is the code:
//Start of JSON Main Content Fetch + Main Content Render
//JSON send_recv of menu array. Assign results to $main_content_b_render
$main_content_fetch=send_recv("menu", array("id" => "17", "fetchContent" => TRUE));
//Renders menu from JSON results.
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
print_r($main_content_fetch);
}
render_main_content($main_content_fetch['results']);
?>
What I can actually get from the other server is the following:
Array ( [id] => 17 [name] => Accessories [reference] => [content] => Array ( [0] => Array ( [type] => Heading1 [content] => BLAH BLAH BLAH TXT TXT TXT [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accblurb ) [1] => Array ( [type] => Image [align] => Left [image] => http://URL.../image/43/webcontent/accshop11.jpg [thumb] => http://URL....com.au/image/thumb/100x100/43/webcontent/accshop11.jpg [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accshop1.jpg ) ) )
I can assign the array values to a variable but it will only assign the first ones, so for example:
if i put this in the function and echo it out
$id = $main_content_fetch['content'];
echo $id;
all I get back is 'Array', what I actually want is the 'BLAH BLAH BLAH TXT TXT TXT' thats located later in the returned info, we actually everything thats located in the last set of brackets...
( [type] => Heading1 [content] => BLAH BLAH BLAH TXT TXT TXT [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accblurb ) [1] => Array ( [type] => Image [align] => Left [image] => http://URL.../image/43/webcontent/accshop11.jpg [thumb] => http://URL....com.au/image/thumb/100x100/43/webcontent/accshop11.jpg [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accshop1.jpg )
What I want to do is to be able to assign basically everything I get back to a variable, as it is. because I think Ill be able to pick what I want out easily enough.. and I don't know of any other way to do it :/
Sorry if its a bit vague, Not very good at explaining myself, but I hope someone can workout what I'm talking about and help.

This is your function. I just replaced print_r with return
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
return $main_content_fetch;
}
lets say you call this function like this. Now you can assign the array in individual variable this way
$data = render_main_content($parameter);
$id = $data['id'];
$name = $data['name'];
......
Hope this helps you. All you need is assign array variable with index to the variable you wish.

sorry, just figured out you have nested array, why not access the required item by $main_content_fetch["content"][0]["content"]?
Anyway by print_r($arr, TRUE) you can print the actual items and see the structure of the array you're dealing .
If I understood you correctly, in order to get the BLA BLA BLA text your code should look like this:
//Start of JSON Main Content Fetch + Main Content Render
//JSON send_recv of menu array. Assign results to $main_content_b_render
$main_content_fetch=send_recv("menu", array("id" => "17", "fetchContent" => TRUE));
//Renders menu from JSON results.
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
//return the second level "content"
return $main_content_b_render[0]['content'];
}
$content = render_main_content($main_content_fetch['results']);
print $content;
?>

You can use something like
foreach (array_expression as $key => $value ) {
// TODO - probably need a recursive version
$$key = $value;
}
When traversing the array, that statement allows you to create new variables in the code.
But, as a rule, you should never rely on the format of the output you get from the other server. My recommendation would be to explicitly extract the information you need from the input, rather just taking it as is and importing it in.
So for example, you would do
$id = input['id'];
You can then check if everything got assigned properly and catch any errors.

You can use below php code solve this issue
$value) { $$key = $value; }
//or....
foreach($user as $key=>$value) { ${$key} = $value; }
?>

First use print_r($arr, TRUE) to print your array when debugging, that will help you a lot :-) (don't forget the TRUE flag!).
You can access any item in the array as you did, but it looks like you're printing $main_content_fetch instead of $main_content_b_render?

Related

Error message: Illegal offset while accessing the array having a different structure than was seen so far

As I kept on resolving the issue I moved further from the last issue that was mentioned here for the people. However, I find it very difficult to get out of the problem accessing the elements in my array as the structure itself seems to be unfamiliar to me. The resultant array is obtained after being assigned with 2 SQL results from the DB as seen below. When looking at the key after printing it out, it seems to appear different from the structures I have seen so far.
If the structure is in the correct form I would like to know how to access article_title,article_desc,article_category from the first row in the array and all the titles from the following rows.I am grateful for your time and the advises. I keep getting the error saying "illegal offset" when trying to access. Please have a look and advise as to what is wrong with it.
$sqlarticle1 = "SELECT article_title, article_desc, article_category FROM crd_article_desc where article_id='$CurrentTitleId'";//Get article based on ID.
$sqlarticle2 = "SELECT article_title FROM crd_article_desc where article_category = '$CurrentCategory'";//Fetch all the categories
$result1 = mysqli_query($con,$sqlarticle1);
$result2 = mysqli_query($con,$sqlarticle2);
$finalarray = array();
while($record1 = mysqli_fetch_array($result1)) {
$finalarray = $record1;
}
while($record2 = mysqli_fetch_array($result2)) {
$finalarray[] = $record2;
}
Structure of the array is
Array (
[0] => Array ( [0] => HTM applications
[article_title] => HTM applications
[1] => Uses of HTML
[article_desc] => Uses of HTML
[2] => HTML
[article_category] => HTML
)
[1] => Array ( [0] => HTML Tags
[article_title] => HTML Tags
)
[2] => Array ( [0] => HTM applications
[article_title] => HTM applications
)
[3] => Array ( [0] => Usage of HTML Elements
[article_title] => Usage of HTML Elements
)
[4] => Array ( [0] => Elements
[article_title] => Elements
)
[5] => Array ( [0] => jobs_codeigniter_page
[article_title] => jobs_codeigniter_page
)
);
Below is how I am trying to access the elements from the array.
foreach ( $finalarray as $key=>$value ){
echo $key;
foreach($value as $innerkey=>$innervalue) {
echo $innervalue['article_title'];
}
}
You don't need to have two foreach loops to go over the results, your array is not that deep.
foreach ( $finalarray as $key=>$value ) {
echo $key;
echo $value["article_title"];
}
Also your first while loop is pointless, as you're not appending to $finalarray. Not sure if that is intentional or not.

Looping through JSON output from Hubspot deals API

I am trying to use the Hubspot API (http://developers.hubspot.com/docs/overview) to loop through all deals and find only those which are current and then do something with those deals.
No matter what I try to do I cannot get my head around how I access the data I need - below is an example of the output.
In the API there are lots of items like dealstage below and the value field under these is what I need to access - for example in this case the deal is closedlost. Another example would be amount which would also have an entry in value so I can then see the deal value.
I want to loop through all deals and for each deal get the dealstage, amount, last update, owner and so on. Each of these are contained in an array of the same layout as [dealstage] below with a value
I have gotten to where I can print the dealstage value for each deal but it doesn't really help - is there a better way of doing this?
foreach ($list['deals'] as $line) {
foreach ($line['properties'] as $row => $value) {
if ($row=="dealstage") {
$stage=$value['value'];
print $stage."<br>";
}
}
}
Example array:
Array
(
[deals] => Array
(
[0] => Array
(
[portalId] => 12345
[dealId] => 67890
[isDeleted] =>
[associations] => Array
(
[associatedVids] => Array
(
[0] => 4051
)
[associatedCompanyIds] => Array
(
[0] => 23456
)
[associatedDealIds] => Array
(
)
)
[properties] => Array
(
[dealstage] => Array
(
[value] => closedlost
)
[createdate] => Array
(
[value] => 1471334633784
)
[amount] => Array
(
[value] => 1000
)
Would something like this be what you are looking for. Loop through the array picking out the items you are interested in and place them in a nice simple array for you to use later when building your email.
$for_email = array();
foreach ($list['deals'] as $line) {
$t = array();
if (isset($line['properties']['dealstage']['value'])) {
$t['dealstage'] = $line['properties']['dealstage']['value'];
}
if (isset($line['properties']['amount']['value'])) {
$t['amount'] = $line['properties']['amount']['value'];
}
if (isset($line['properties']['createdate']['value'])) {
$t['createdate'] = $line['properties']['createdate']['value'];
}
// any other data you want to capture
// put this data in the new array
$for_email[] = $t;
}
// check what the new array looks like
print_r($for_email);

Echo a specific value on a very nested array

I have a function that generate an array (I did not made that function, comes from an API) and then saves it to a variable($customerList). I need to display just one value of an entire nested array; this array contains all this code (shown with print_r($customerList);) :
Array
(
[0] => Customer Object
(
[status:protected] =>
[creation_date:protected] => 2016-01-14T12:07:07-06:00
[balance:protected] =>
[clabe:protected] => 321654qweasd
[derivedResources:protected] => Array
(
[cards] => 123123123123
//a lot of code
How can I display just the value on "[cards]" using echo?
I have tried
//the for loop {
echo $customerList['0']['derivedResources:protected']['cards'];
And
//the for loop {
echo $customerList['0']['derivedResources']['cards'];
But it just display nothing. I haven't seen an array like this, so maybe is just a newbie mistake.
I think that "protected" thing has something to do with; but if I can display it, I can read/access it, right?
If any of you need the entire array (it's very long) I can put it here.
Thanks.
I haven't seen an array like this
It is an array of objects. Learn something about OOP.
This should work:
echo $customerList[0]->derivedResources['cards'];
Based on the print_r:
Array
(
[0] => Customer Object
(
[status:protected] =>
[creation_date:protected] => 2016-01-14T12:07:07-06:00
[balance:protected] =>
[clabe:protected] => 321654qweasd
[derivedResources:protected] => Array
(
[cards] => 123123123123
//a lot of code
We can simulate:
<?php
$CustomerObject = new \stdClass;
$derivedResources = new \stdClass();
$CustomerObject->derivedResources = ["cards" => 123123123123];
$customerList = [$CustomerObject];
// print_r($customerList);
echo $customerList[0]->derivedResources['cards'];
Which, uncommenting the print_r results in:
Array
(
[0] => stdClass Object
(
[derivedResources] => Array
(
[cards] => 123123123123
)
)
)
123123123123

Extracting Data from Multidimensional Array

I'm working with the S3 library found here: http://undesigned.org.za/2007/10/22/amazon-s3-php-class/
It works great, but I'm having a tough time extracting the data I need from the returned array results. I'm grabbing the bucket contents, and it returns something like this:
Array (
[sample_mpeg4.mp4] => Array (
[name] => sample_mpeg4.mp4
[time] => 1378922417
[size] => 245779
[hash] => dc77a8de8c091c19d86df74eb7
)
[steve.jpg] => Array (
[name] => steve.jpg
[time] => 1381270899
[size] => 61109
[hash] => a008368bf58515775c45e75c54
)
[stev-small-photo1.png] => Array (
[name] => stev-small-photo1.png
[time] => 1381270891
[size] => 680353
[hash] => ddcb22a103d4fa8360083ad70a
)
)
Ok, cool. I'm querying and matching the key to pull out specific info on that particular piece of media. My code for that looks like this:
$searchVar = "steve.jpg";
$s3 = new S3(awsAccessKey, awsSecretKey);
$bucket_contents = $s3->getBucket("uploads.bucket.com");
//fetch array of current files
$searchAssetsBucket = array_keys($bucket_contents);
foreach ($searchAssetsBucket as $value) {
if($value == $searchVar) {
echo $value['time'];
}
}
if(empty($returnValue)) {
$returnValue = "Sorry no results for <b>$searchVar</b>.";
}
This doesn't work for me. What I'm really trying to do is get the code to return the name/time/size/hash vars from the [steve.jpg] array once it's been matched. I'm not sure what I'm doing wrong here, but this code simply returns "s".
Does anyone have any ideas? I'm truly at a lose here...
I would do something like this:
$myArray=$yourOriginalS3Array;
$searchVar='Steve.jpg';
// set up default/blank data in $matchedArr
foreach ($myArray as $key => $val)
{
if($key == $searchVar) {
$matchedArr=$val;
}
}
echo "The name is ".$matchedArr['name']." and the size is ".$matchedArr['size']."<br>";
This way, you are checking the keys of your original array, and if matched, returning an array that matches the second level of the original array which can be easily accessed in your code.

CakePHP 1.2.6 / PHP5.2.12 Error in Array Loop in Assignment by Reference

I'm working on retrieving a stack of data and for some reason some of the data gets corrupted. For instance, I've got some Post models that each are related to Comment models (hasMany), and each of the Comment models belongsTo a User. When retrieving the data, here's what I get from the database for the comments:
[Post] => Array
(
)
[Comments] => Array
(
[0] => Array
(
[content] => "2010 has definitely been a busy year!"
[created] => 2010-02-10 13:47:15
[user_id] => 18
[post_id] => 1
[User] => Array
(
[id] => U8
[username] => Uace
[first_name] => Uace
)
[_explicitType] => Comment
)
[0] => Array
(
[content] => "I can't wait..."
[created] => 2009-12-10 13:57:36
[user_id] => 18
[post_id] => 1
[User] => Array
(
[id] => U8
[username] => Uace
[first_name] => Uace
)
[_explicitType] => Comment
)
)
The first character of each of the Comments[i][User] arrays has been replaced with a capital U, though in each case it should be different (such as ID of 18, username of Jace, etc).
I traced it back to an array manipulation I was working with to assign an _explicitType field for Flex interaction (Thanks, Paweł Mysior!) in the afterFind() function. Here's the loop where I stuck in the _explicitType:
if (is_array($results)) {
foreach ( $results as &$item )
{
$item['_explicitType'] = $this->name;
}
} else {
$item[$this->name]['_explicitType'] = $this->name;
}
I assume it has to do with the assignment by reference, but I can't think of why it is happening.
It is very strange.
Set debug to 2 in core.php and look in the sql log at the bottom of the page, maybe you'll find something there. Also look through all models (app, post, user, comment). There might be some beforeFind() that are causing this to happen. Does it also happen when you do a simple User->find()?
Btw. how do you retrieve data here?
I think found the issue. I moved the check for the array inside the foreach() and that seems to be working correctly now. I assume this is because on non-array items, it actually broke things. Here's my altered loop with logging on the test cases:
foreach ( $results as &$item )
{
if(is_array($item)) {
$item['_explicitType'] = $this->name;
} else {
$copy = $item;
$copy['_explicitType'] = $this->name;
$this->log($copy, LOG_DEBUG);
}
}
And sure enough, it logged the data with capital U's replacing the first letter.

Categories