How can i get json in php - php

I get an array from json but i don't know how to get bookTitle and url.
How can i read this items in the arrays ?
$data = file_get_contents('C:\Users\rsanchro\Desktop\ftp brasil4-9-2015\moderna_plus-historia\MPCH-C05-P1-1.0.1-ZIP-PT\resource.json');
$datos = json_decode($data, true);
print_r($datos);die;
Results:
Array
(
[topBarColor] => #000000
[bookId] => 2aef55bf3a9dec377b4f16a8048c7f84
[bookTitle] => História
[unitId] => MPCH-C05-P1
[unitTitle] => 108-127-MPCH-C05-P1-M
[unitResources] => Array
(
[0] => Array
(
[type] => 03
[url] => resources/mphis_c06av_escultura_ontem.mp4
[urlToShowInsideUnit] => #/compId/id0a33b2a0471e0f444bc0a88b5bb55714
[title] => A escultura ontem e hoje
[page] => 123
)
)
)

Use this
print_r(utf8_decode($datos['bookTitle']));
if(is_array($datos['unitResources']) && count($datos['unitResources']) > 0){
foreach($datos['unitResources'] as $key => $value){
print_r($value['url']);
}
}

if you are having only single data use the following
$bookTitle=$datos['bookTitle'];
$url=$datos['unitResources'][0]['url'];
If you have more than one data in the array then use the following
foreach($datos as $dato){
$bookTitle=$dato['bookTitle'];
$urls=array();
foreach($datos['unitResources'] as $url){
$urls[]=$url['url'];
}
echo '<br>Book Title :'.$bookTitle;
echo '<br>urls :';
foreach($urls as $url){
echo $url.'<br>';
}
}
For your example array which you mentioned. you can use the first method.
but since you are working with array better use the 2nd method.

Try this
echo "Title:".$datos['bookTitle']; //To print book title
//To print url
if(is_array($datos['unitResources']) && count($datos['unitResources']) > 0){
foreach($datos['unitResources'] as $key => $value){
echo "URL:".$value['url'] ;
}
}

I'd also recommend taking a look at the jsonselect library. It provides an intuitive selection syntax that is modeled after CSS selector syntax.
JSON Select project site:
http://jsonselect.org/#overview
PHP implementation:
https://github.com/observu/JSONselect-php

Related

Create PHP Variables dynamically in foreach loop

I am just trying to create PHP variables dynamically. below is the code I have tried.
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
while
$BrickTerritorys is
[1] => stdClass Object
(
[id] => 119
[TerritoryID] => HYD-2-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 40.00
[BPCode] => bp00066
[GroupCode] => CMD
)
[2] => stdClass Object
(
[id] => 36330
[TerritoryID] => HYD-1-CMD
[BrickCode] => 16
[BrickName] => BUHURO
[Weightage] => 60.00
[BPCode] => bp00066
[GroupCode] => CMD
)
When I print in the last, nothing gets printed. Any help is much appreciated, please.
Thanks in advance
${"T$index"} as well as ${"Weightage$index"}
you don't need the dot,or you can use ${'T' . $index}. look at the dot. it's not addition operation while it in "". following this code:
if($BrickTerritorys)
{
foreach($BrickTerritorys as $index=>$BrickTerritory)
{
${"$T.$index"}= $BrickTerritory->TerritoryID;
${"'Weightage'.$index"} = $BrickTerritory->Weightage;
}
echo $T1."-".$T2."--".$Weightage1."---".$Weightage2; exit;
}
Try changing those lines like this:
${"T$index"}= $BrickTerritory->TerritoryID;
${"Weightage$index"} = $BrickTerritory->Weightage;
In your code ${"$T.$index"} $T is searching for variable, and you should get undefined variable $T, so you have to remove $ sign, if you want to have T1, T2 variables.
After that, ${"'Weightage'.$index"}, the apostrophes between Weightage means your variable will look like 'Weightage'.1, 'Weightage'.2.. and etc.
This can be done a few different ways without variable variables AND produce a completely dynamic outcome.
Here's one: (Demo)
$array = (array)$BrickTerritorys; // cast as array
$tids = array_column($array, 'TerritoryID'); // isolate column data
$was = array_column($array, 'Weightage'); // isolate column data
$merged = array_merge($tids, $was); // add 2nd array data after 1st array data
foreach ($merged as $i => $v) {
echo str_repeat('-', $i) , $v; // increase hyphens on each iteration starting from 0
}
Output: (notice, no hardcoded echo)
HYD-2-CMD-HYD-1-CMD--40.00---60.00

selecting value of particular index with PHP foreach

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?
You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.
foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

PHP how to properly loop through json with multiple levels as object

Here is the Json data stored in variable $json
[Data] => Array
(
[id_number] => Array
(
[value] => 123445567
[link] => 1234556
[class] =>
)
[date] => Array
(
[value] => 04-18-14
[link] => 1234556
[class] =>
)
Currently I access the lower levels like this:
foreach($json['Data'] as $data) {
foreach ($data['id_number'] as $id) {
print $id['value'];
}
}
There is only one result for id_number and only one result for date. Do I really need this second foreach loop? Isn't there a way to access it by just going to the lower level as an object so it would be something like
print $data->id_number->value
Thank you.
Since you have decoded the JSON string as an array you could do
foreach($json['Data'] as $data) {
print $data['id_number']['value'];
}
If you had decoded it into an object (don't set the second parameter to be true) then you could simply do it like you mentioned
foreach($json->Data as $data)
print $data->id_number->value;
Manual
You can retrieve the elements individually (without looping) by:
$id_number = $json['Data']['id_number']['value'];
$date = $json['Data']['date']['value'];
//etc ...
You can use:
$json['Data'][idnr]->value
If you know the id that is ofc, else you will have to loop

Access corresponding value in PHP array given a certain known value

supposing I have an array like the one below:
Array
(
[0] => Array
(
[id] => 1
[title] => Group1
[description] => This is the group1.
)
[1] => Array
(
[id] => 2
[title] => Group2
[description] => This is group2.
)
)
Supposing the title is known as "Group2". How would I able to determine using PHP its equivalent description (that is "This is group2") if it doesn't have any idea of its ,key,id, etc. only the title?
Thanks for any help.
Try this :
$title = "Group2";
foreach($your_array as $val){
if($val['title'] == $title){
echo $val['description'];
break; //cut back on unnecessary looping
}
}
Try like this
foreach($myarray as $val){
if($val['title'] == "Group2"){
echo 'This is description '.$val['description'];
}
}
You'll have to iterate over the main array and scan it for that title.
Assuming your main array is called $groups :
$title = 'Group2';
foreach($groups as $key => $group){
if ($group['title'] == $title){
$groupDescription = $group['description'];
// if you need to reference this group again, save it's key.
$groupKey = $key;
}
}
You can insert a break command after you have found the group you are looking for to terminate the loop so that it will not continue to scan the array after you have found the one you are looking for.

Echo a multidimensional array in PHP

I have a multidimensional array and I'm trying to find out how to simply "echo" the elements of the array. The depth of the array is not known, so it could be deeply nested.
In the case of the array below, the right order to echo would be:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
This is the array I was talking about:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)
<pre>
<?php print_r ($array); ?>
</pre>
It looks like you're only trying to write one important value from each array. Try a recursive function like so:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
You could also make it a little more dynamic and have the 'comment_content' and 'child' strings passed into the function as parameters (and continue passing them in the recursive call).
Proper, Better, and Clean Solution:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
You simply call in this helper function traverseArray($array) in your current/main class like this:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
source: http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/
print_r($arr) usually gives pretty readable result.
if you wanted to store it as a variable you could do:
recurse_array($values){
$content = '';
if( is_array($values) ){
foreach($values as $key => $value){
if( is_array($value) ){
$content.="$key<br />".recurse_array($value);
}else{
$content.="$key = $value<br />";
}
}
}
return $content;
}
$array_text = recurse_array($array);
Obviously you can format as needed!
There are multiple ways to do that
1) - print_r($array); or if you want nicely formatted array then
echo '<pre>'; print_r($array); echo '<pre/>';
//-------------------------------------------------
2) - use var_dump($array) to get more information of the content in the array like datatype and length.
//-------------------------------------------------
3) - you can loop the array using php's foreach(); and get the desired output.
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}
Try to use var_dump function.
If you're outputting the data for debugging and development purposes, Krumo is great for producing easily readable output. Check out the example output.
Recursion would be your answer typically, but an alternative would be to use references. See http://www.ideashower.com/our_solutions/create-a-parent-child-array-structure-in-one-pass/

Categories