Decode JSON each array to PHP [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have some encoded json like this:
[
{"title":"root", "link":"one"},
{"title":"branch", "link":"two"},
{"title":"leaf", "link":"three"}
]
I want to decode that JSON into PHP output like:
title || link
root || one
branch || two
leaf || three
I tried this but doesn't work:
$list = json_decode($json);
foreach ($list as $list => $value) {
echo $list->title;
echo $list->link;
}

try changing your foreach loop to this.
foreach ($list as $key => $value) {
echo $value->title." || ";
echo $value->link." ";
echo nl2br("\n");
}
Hope this Works for you.

What you did is looping the keys and values seperated and than you tried to get the values from the keys of the stdClass, what you need to do is looping it as an object. I also used json_decode($json_str, true) to get the result as an array instead of an stdClass.
$json_str = '[{"title":"root","link":"one"},{"title":"branch","link":"two"},{"title":"leaf","link":"three"}]';
$json_decoded = json_decode($json_str, true);
foreach($json_decoded as $object)
{
echo $object['title'];
echo $object['link'];
}

Code :
$list = json_decode($json);
foreach ($list as $item) {
echo $item->title . ' || ' . $item->link . '<br>';
}

Related

illegal offset type in php on vscode no error, but on page says that error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 months ago.
Improve this question
hello i'm running into a problem, it says on the browser illegal offset type,
im declaring an array this way:
$matriculas = [
1 => ["99-99-99", "D"],
2 => ["88-88-88", "D"],
];
and the error is in this line :
$series[$option] = [$option['matricula'],$option['type']];
the function looks like this:
<?php
$query ="SELECT * FROM matriculas";
$result = $con->query($query);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);
}
$series = array();
foreach ($options as $option) {
$series[$option] = [$option['matricula'],$option['type']];
}
?>
<select name="id">
<option>Select matricula</option>
<?php
foreach ($series as $ID => $values) {
?>
<option name=<?php $ID ?> > <?php echo $values[0]; ?></option>
<?php
}
>
</select>
how can i make it right? thanks in advance for your help
It's almost right.
Based on the subsequent foreach ($series as $ID => $values), I think you want this instead:
foreach ($options as $option) {
$series[$option['id']] = [$option['matricula'], $option['type']];
}
But unless you're going to use the $option['type'] value for something else later, it could be simplified to
foreach ($options as $option) {
$series[$option['id']] = $option['matricula'];
}
Option in your case is an array and you cannot make an array the key of the index. So instead of $series[$option] you should do $series[$option['matricula']] or $series[$option['type']] as its a single value.
instead of that why you don't modify this to fit?
so then where you have foreach ($series as $ID => $values) { to replace that with echo $sum;
so try to modify the piece in this way (you may modify it in case isn't work but the idea is to not fill the memory with a new array but what you read already to sum it and output text as template insertion)
$sum='';
$series = array();
foreach ($options as $option) {
//nope! $series[$option] = [$option['matricula'],$option['type']];
$sum.=<<<opt
<option name="{$option['matricula']}">{$option['type']}</option>
opt;
}

Iterate through Array and extract data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to iterate through this array http://2of1.com/zee/ZEES%20SMS%20SERVICE.html and extract the data.
I was using:
foreach ($graphObject['data'] as $key => $value){
$string = $value->message;
$link = $value->actions[0]->link;
$pic = $value->picture;
$post_id = $value->id;
}
But it is no longer working after i added a second source to the array.
When i try:
foreach ($graphObject as $key => $value){
$string = $value->data[0]->message;
$link = $value->data[0]->actions[0]->link;
$pic = $value->data[0]->picture;
$post_id = $value->data[0]->id;
I get only the first entry values from data[0] and it does not iterate through all the data. What i need is the data from data[0] data[1] data[2] data[3]... etc etc... Please help. Thank you!
Probably something like
foreach ($graphObject as $keyEntry => $entry){
foreach( $entry->data as $data ) {
echo $data->picture, "<br />\r\n";
foreach( $data->actions as $action ) {
echo $action->link, "<br />\r\n";

How to delete an array of array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an array like this :
[[a,b],[c,d]]
How can I delete the outer array so it becomes:
[a,b],[c,d]
I tried using unset but cannot find a solution.
i got this answer by asign arrays in loops to another variable.. so how can i access the loops outside the loop it self?
foreach($arr3 as $key => $value)
{
$newArr[$key] = $value;
echo json_encode($value); // this will answer my question
}
echo json_encode($value); // when i echo outside loop it will not display as inside loop
Simple way to do this is as below.
foreach($array as $key => $value)
{
$newArr[$key] = $value;
}
$newArr contains new array which you are asking.
Comment Response
You can also con cat it.
$concat = "";
foreach($arr3 as $key => $value)
{
$newArr[$key] = $value;
$concat .= json_encode($value).',';
}
echo rtrim($concat,',');
You should not delete the outer array. You can simply access the index of the array and cast it to another array.
As an example;
$arr = array(array('x','y'),array('z'));
You can access this with;
$arr[0];
$array2=$array[0];
$array3=$array[1];
unset($array);

Add new values to foreach loop from inside the loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
Is possible to add new values to the array that the foreach is working with? So it will run (n+x) where n is the number of elements of the array before the foreach starts and x is the number of elements that were added to the array.
Yes, I tested.. and looks like NO.. so I'd like to know if I can do something to this work.
foreach($pages_to_visit as $key => $source){
global $products;
$links = baixarSource($source);
foreach($links as $link){
global $products;
global $pages_to_visit;
if(preg_match("/somestore\.com/i", $link)){
if(!in_array($link, $pages_to_visit)){
$pages_to_visit[] = $link;
}else if(preg_match("/\/produto\//i", $link) && !in_array($link, $products)){
$products[] = $link;
echo $link."\n";
}
}
}
unset($pages_to_visit[$key]);
sleep(0.2);
}
As you already figured out, using foreach() it is not possible, however when you use for() the task becomes quite easy:
for ($i=0; $i<count($array); $i++) {
//code
}
This is due to count($array) being (re)calculated before every iteration. You can also use a variable that you increment yourself (incrementing is a way easier task than counting an array)
$max = count($array);
for ($i=0; $i<$max; $i++) {
//code
//when push an element just do $max++;
}
Of course this will only work with numerical indices but that seems to be the case here.
You need to specify the "runner" variable as a reference in the foreach code if you want to modify the array itself from within the foreach.
http://us2.php.net/manual/en/control-structures.foreach.php
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
Example (will only count to 9):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as $blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}
Example2 (this time it will count to 10 using the additional element added from inside the foreach):
$arr = array(1,2,3,4,5,6,7,8,9);
$makeArrayLonger = true;
foreach ($arr as &$blubb)
{
if ($makeArrayLonger)
{
$arr[] = 10;
$makeArrayLonger = false;
}
echo $blubb;
}
Not sure if I get your question right... I think what you try to do doesn't make much sense at all any way.
echo $countBefore = count($data);
foreach ($data $as $value) {
$data[] = 'Some new value';
}
echo $countAfter = count($data);

how to get values from the content? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
{"prereqs":{"prereq":{"type":"prereq_check","value":"submerging_island_feature_enabled"}},"divisions":{"division":[{"items":{"item":[{"name":"rhino_shell","rarity":"common"},{"name":"walrus_wavy","rarity":"special"},{"name":"hippo_fancyshell","rarity":"rare"},{"name":"rhino_jellyfish","rarity":"superRare"}]},"name":"rubyCount_30"},{"items":{"item":[{"name":"walrus_clam","rarity":"common"},{"name":"hippo_nautical","rarity":"special"},{"name":"giraffe_coral","rarity":"rare"},{"name":"elephant_starburst","rarity":"superRare"}]},"name":"rubyCount_40"},{"items":{"item":[{"name":"giraffe_waverider","rarity":"common"},{"name":"pony_sea","rarity":"special"},{"name":"magicdeer_seadeer","rarity":"rare"},{"name":"pony_seaprincesscorn","rarity":"superRare"}]},"name":"rubyCount_50"},{"items":{"item":[{"name":"bigcat_crystallion","rarity":"common"},{"name":"magicdeer_midnightdeer","rarity":"special"},{"name":"horse_ofthesea","rarity":"rare"},{"name":"horse_wingedsea","rarity":"superRare"}]},"name":"rubyCount_60"}]},"crafting":{"recipes":{"recipe":[{"name":"qdke"},{"name":"sb1p"},{"name":"cb8v"}]}},"listEndDate":"07/13/2015","currencyItem":{"name":"healingpotionbottle"},"feed":{"throttleTime":"21600"},"name":"submerging_island"}
To get you going my 2 cents. First off, Welcome, please read How to ask a good question
First you need to decode the json string in to an array. with that array you can get the values.
<?php
$json = '{"prereqs":{"prereq":{"type":"prereq_check","value":"submerging_island_feature_enabled"}},
"divisions":{"division":[{"items":{"item":[{"name":"rhino_shell","rarity":"common"},
{"name":"walrus_wavy","rarity":"special"},{"name":"hippo_fancyshell","rarity":"rare"},
{"name":"rhino_jellyfish","rarity":"superRare"}]},"name":"rubyCount_30"},
{"items":{"item":[{"name":"walrus_clam","rarity":"common"},{"name":"hippo_nautical","rarity":"special"},
{"name":"giraffe_coral","rarity":"rare"},{"name":"elephant_starburst","rarity":"superRare"}]},"name":"rubyCount_40"},
{"items":{"item":[{"name":"giraffe_waverider","rarity":"common"},{"name":"pony_sea","rarity":"special"},
{"name":"magicdeer_seadeer","rarity":"rare"},
{"name":"pony_seaprincesscorn","rarity":"superRare"}]},"name":"rubyCount_50"},
{"items":{"item":[{"name":"bigcat_crystallion","rarity":"common"},{"name":"magicdeer_midnightdeer","rarity":"special"},
{"name":"horse_ofthesea","rarity":"rare"},
{"name":"horse_wingedsea","rarity":"superRare"}]},"name":"rubyCount_60"}]},"crafting":{"recipes":{"recipe":[{"name":"qdke"},
{"name":"sb1p"},{"name":"cb8v"}]}},"listEndDate":"07/13/2015","currencyItem":{"name":"healingpotionbottle"},"feed":{"throttleTime":"21600"},"name":"submerging_island"}';
//decode the json
$decoded = json_decode($json, true);
// uncomment if you want it to be easier to read
// echo "<pre>";
// print_r($decoded);
// echo "</pre>";
//if you want the singe value, i.e. name of the first item.
echo "If you want a sinle value:<br>";
echo $decoded['divisions']['division'][0]['items']['item'][0]['name'] . "<br>";
//to get all names from one item you need to use a foreach() loop.
echo "<br>if you want all names from one item:<br>";
foreach($decoded['divisions']['division'][0]['items']['item'] AS $value){
echo $value['name'] . "<br>";
}
//to get all names we need to use 2 foreach loops because this is nested in multiple arrays
echo "<br>if you want all names from all items:<br>";
foreach($decoded['divisions']['division'] AS $value){
foreach($value['items']['item'] AS $value){
echo $value['name'] . "<br>";
}
}
?>

Categories