How to get content from array - php

I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)

Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']

Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;

To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.

Related

PHP - retrieving and parsing this JSON file

I'm looking for a way to access this JSON file data. What I'm interested in is to extract the property named documentjsonblob, as below.
object(Quadrem\Model\Order)[201]
protected '_dateCreated' => null
protected '_buyerCode' => null
array (size=2)
2415 =>
array (size=23)
'#storeid' => string '813' (length=3)
'#active' => string '1' (length=1)
'#created' => string '2013-11-25 12:28:21' (length=19)
'documentjsonblob' => string '{"HEAD":{"ORDERSEQUENCE":"0","TOTAL_TAX":7.9,"TOTAL_AMOUNT":86.9,"NUMBER":"AKMon3","TYPE":"NB","TYPE_NAME":"Standard PO","SUPPLIER":"0000002122","CREATED":"2013-04-29T12:00:00Z","CONTRACT_NUMBER":"","EXTERNAL_REFERENCE":"","CONTACT_PERSON":"Caroline Howlett","COMMENT":[""],"CURRENCY":"AUD","DELIVERY_TERMS":"DeliveryCondition|","PAYMENT_TERMS":[{"TEXT1":"21st day of next month after receipt"}],"NET_VALUE":79.0,"DELIVERY_ADDRESS":{"NAME_1":"KGTP FACILITY","NAME_2":"GAS TREATMENT PLANT","NAME_3":"KGPF","POSTAL_CODE":"6714","CITY":"Karratha","STREET":"Withnell Bay","REGION":"AUWA","REGION_NAME":"AUWA","COUNTRY":"AU"}]}' (length=3029)
'documenttype' => string 'PO' (length=2)
1890 =>
array (size=23)
'#storeid' => null
'#active' => null
I'm not quite sure which kind of an encoded JSON file this is by the way it looks. Would appreciate it if somebody could help.
Thanks.
Since in the comment you have mentioned it is the out put of var_dump and you want to get documentjsonblob, let's follow this:
On first line you have object(Quadrem\Model\Order)[201], that means you var_dumped an object, say $my_obj
On line four array (size=2) says you have an array, and what you need is located in the first element of the array, so $my_obj[0]
$my_obj[0] holds an associative array, and the desired index is documentjsonblob, so we can get the String representation as:
$my_arr = $my_obj[0];
$json_str = $my_arr['documentjsonblob'];
Now $json_str holds the String representation, to convert it to an PHP object:
$json_obj = json_decode($json_str);
So now $json_obj holds the object you want.

Accessing an array inside of an array

When trying to access an array inside an array, only NULL is output.
My Code:
$aStats = array();
$aStats['hd'] = array();
$aStats['hd'][] = array
(
'dev' => $device,
'total' => $total,
'used' => $used,
'free' => $free,
'used_perc' => $used_perc,
'mount' => $folder
);
echo $aStats['hd']['free'];
When using json_encode, the values are displayed correctly:
die( json_encode( $aStats ) );
Where is my mistake?
Replace these lines:
$aStats['hd'] = array();
$aStats['hd'][] = array
With this:
$aStats['hd'] = array
You appear to be accessing your array ($aStats['hd']['free'];) as if the value of hd is an associated array, but using [] creates a new integer index in the array, and stores the value in that index. Joe Walker's answer shows what happens instead, that you have an associative array pointing to an indexed array pointing to another associative array, rather than the associative to associative array you suggest you're trying to use in your echo statement.
This is a practical tip that will let you find out where is the issue easly, all you need to do is:
var_dump($aStats);
This will output:
array (size=1)
'hd' =>
array (size=1)
0 =>
array (size=6)
'dev' => string 'SomeDevice' (length=10)
'total' => string '10000' (length=5)
'used' => boolean true
'free' => boolean false
'used_perc' => string 'none' (length=4)
'mount' => string '/some/directory/here/' (length=21)
Now you know you can access this element using
$aStats['hd'][0]['free'];
This will return null in your question because your variables are not yet initialized, but I guess you do have them initialized in your code, hope this helps.

how to parse the json array elements using for loop to get the values one by one

i have a json array wherer i would like to pasre the json till the last element by using for loop for that i would like to get the number of array elements in the json array ,i have more than 3 objects in anarray ,so i am confused how to parse the json till the last element,
i can say you the idea
Count($json);
echo count;
for(i=0;i<l=count($json);i++)
{
then print the value of each key
}
i am stuck ,because there is no fixed lenght for the json i am getting as it is a server response it may return one object one may be twice or thrice or many ,so i thought it would be better to do with for loop ,as a json contain more than one json with 3 keys ,such as country can have more than one state,and one state can have more than one district ,plaese help me,i am stuck with question for last 2 days
thank you
An idea :
function printJson($json) {
foreach($json as $index=>$value) {
if(is_array($value)) {
printJson($value);
} else {
echo 'Value :'.$value.'<br />';
}
}
}
$stringJson = "{'location':[{...}]}"; //for example
printJson(json_decode($stringJson));
You can alternatively decode the json tring using json_decode() which will give u a php variable which u can then easily iterate over using php.
eg.
$string = '{"image":"fox.png","puzzlepieces":{"f":{"puzzlepiece":"one","position":"top:121px;left:389px;"},"x":{"puzzlepiece":"three","position":"top:164px;left:455px;"},"o":{"puzzlepiece":"two","position":"top:52px;left:435px;"}}}';
var_dump(json_decode($string));
will output as
object(stdClass)[1]
public 'image' => string 'fox.png' (length=7)
public 'puzzlepieces' =>
object(stdClass)[2]
public 'f' =>
object(stdClass)[3]
public 'puzzlepiece' => string 'one' (length=3)
public 'position' => string 'top:121px;left:389px;' (length=21)
public 'x' =>
object(stdClass)[4]
public 'puzzlepiece' => string 'three' (length=5)
public 'position' => string 'top:164px;left:455px;' (length=21)
public 'o' =>
object(stdClass)[5]
public 'puzzlepiece' => string 'two' (length=3)
public 'position' => string 'top:52px;left:435px;' (length=20)
My xdebug extension is on in WAMP so your var_dump might be a little differently formatted but overall you'd get a php variable from the array which u can iterate using foreach or other loops.
Read more on json_decode here

access associative array

I am using Code Igniter and I get following data structure after executing a query at DB
array
'application' =>
array
0 =>
object(stdClass)[19]
public 'app_id' => string '16' (length=2)
public 'app_name' => string 'dddddddd' (length=8)
public 'app_title' => string 'sdfsdf' (length=6)
public 'app_comments' => string 'sdfsdf' (length=6)
public 'active_flg' => string 'N' (length=1)
I know one way to access the values is
foreach($application as $key => $value)
$value->app_id
But I know that I will get only one record each time so I want to access the elements without using foreach.
I have tried to $application->app_id and $application['app_id'] but I keep getting error.
Can anybody please help me to understand how to access the data directly??
You are using multidimensional mixed type of array, with numeric indexing on the second level. SO, while accessing the values, you have to use them too. Like
echo $array['application'][0]->app_id;
A simple example to show you the structure of your array and how you might access it...
$objArray = array('app_id' => 7, 'app_name' => 'apps demo', 'app_title' => 'apps demo title');
$applicationArray = array('application' => array((object)$objArray));
// access the array
print $applicationArray['application'][0]->app_id;
Are you getting that result by doing the following?
$res = $this->db->query('select * from application limit 1')->result();
If so, you can put that result into an object by doing:
$app = $this->db->query('select * from application limit 1')->row();
This way you can access the properties as follows:
echo $app->app_id;
You should check out codeigniters manual on getting results.

Problem inserting string into array

i'm trying to insert an implode generated string to an array that then later be used for json implementation
the implode generated string is look like this
'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]
i would like to used it in this code
$this->_JsonArr[]=array($Generated string);
to achieve something like this
$this->_JsonArr[]=array('id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]);
instead i got something like this
$this->_JsonArr[]=array(" 'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]");
seem like generated string is treated as one element as key and value pair.
obviously i can get expected output from mysql because of this, can anybody help me with this
Why do you need to implode anything? Just pass the array:
$this->_JsonArr[] = your-non-imploded-array-here;
I think a full solution to what you want to do is something like this (i.e., the third code box in your question):
$row = array(
'id' => $this->_SqlResult[0],
'UserId' => $this->_SqlResult[1],
'Msg' => $this->_SqlResult[2],
'MsgStamp' => $this->_SqlResult[3]
);
$this->_JsonArr[] = $row;
$this->_JsonArr[]=array($Generated
string);
Looks like you want use arrays keys and values, but as I see you put into array plain string with expectation that array parse your plain string in format: keys => values.
You can try create array like below:
$this->_JsonArr[ $Generated_key ] = array( $Generated_value );
(Please correct me if I wrong understand your question).

Categories