[ / / / / / / / / / / / / / ] [ dir / abdl / ausneets / cafechan / cyoa / htg / kpop / leftpol / strek ][Options][ watchlist ]

/prog/ - Programming

Programming board
You can now write text to your AI-generated image at https://aiproto.com It is currently free to use for Proto members.
Name
Email
Subject
Comment *
File
Select/drop/paste files here
* = required field[▶ Show post options & limits]
Confused? See the FAQ.
Expand all images

File (hide): d4b6c9b3e747a3d⋯.png (2.87 KB, 225x225, 1:1, descarga (1).png) (h) (u)

[–]

6a60e8 (2) No.4982[Watch Thread][Show All Posts]

I have problems decoding a json in 8ch.net

https://8ch.net/b/1.json


<?php
$url = "https://8ch.net/b/1.json";
$json = file_get_contents($url);
$json_data = json_decode($json,true);
echo "Threads".$json_data["threads"]."<br>";
?>

it says only invalid conversion in array to string. I don't understand why I can't print Threads in the array

1c2bbc (2) No.4984

You could have just fucking googled it: https://stackoverflow.com/questions/7490488/array-to-string-php

PHP is shit, but not being able to implicitly treat an array like a string is a good thing. And note that threads there are arrays of arrays, so you have to actually parse the structure to get what you want. You can implode it (which is basically an array join) or you can convert it back to json or something. I'd recommend using classes to properly build an object hierarchy. If you're lazy, you can just extract exactly what you need:

<?php
$url = "https://8ch.net/b/1.json";
$json = file_get_contents($url);
$json_data = json_decode($json,true);

// Get either the subject or the first 30 characters of the post
$get_title = function($thread) {
$post = $thread['posts'][0];
if (isset($post['sub'])) {
return $post['sub'];
} else {
return substr(strip_tags($post['com']), 0, 30);
}
};

echo "Threads: <br>" . implode("<br>", array_map($get_title, $json_data["threads"])) . "<br>";
?>

Holy shit PHP sucks, though.


6a60e8 (2) No.4991>>4994

Why I can't access inside of the array of post


<?php

$url = "https://8ch.net/tech/res/877945.json";
$json = file_get_contents($url);
$json_data = json_decode($json,true);
foreach($json_data as $post){

echo "json -> ".$post['no'];

}
?>


1c2bbc (2) No.4994

>>4991

Because you're iterating over the whole object, which gives you the value of the "posts" element. You want to iterate over the "posts" array itself, not the whole hash:

<?php

$url = "https://8ch.net/tech/res/877945.json";
$json = file_get_contents($url);
$json_data = json_decode($json,true);
foreach($json_data['posts'] as $post){

echo "json -> ".$post['no'];

}
?>




[Return][Go to top][Catalog][Screencap][Nerve Center][Cancer][Update] ( Scroll to new posts) ( Auto) 5
3 replies | 0 images | 2 UIDs | Page ???
[Post a Reply]
[ / / / / / / / / / / / / / ] [ dir / abdl / ausneets / cafechan / cyoa / htg / kpop / leftpol / strek ][ watchlist ]