I'm trying to create JSON feed from one site which i want to decode on another. The problem is there seem to be to many array[0], so it is hard to loop through it and count how many objects there are.
How can i do this encode and decode without getting all these arrays, to make it easier to count the amount of objects and loop through it.
at the moment i'm encoding it like this:
$data = array();
foreach ($posts as $post) {
$r = str_replace("\n",'', shorten_txt($post->post_content, 500));
$n = str_replace("\r", '', $r);
$post_data = array(
'title' => get_the_title($post->ID),
'link' => get_permalink($post->ID),
'image' => catch_that_image(),
'content' => $n,
'time' => get_the_date( $d)." ". get_the_time( $d));
$data[] = (array('item' => $post_data));
}
echo json_encode($data);
This gives this output:
[
{
item: {
title: "Hello world!",
link: "http://URL/wordpress/?p=1",
image: "http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png",
content: "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
time: "April 17, 2014 5:32 pm"
}
}
]
When i decode this i get this:
Array ( [0] => Array ( [item] => Array( [title] => Hello world! [link] => http://URL/wordpress/?p=1 [image] => http://URL/wordpress/wp-content/uploads/2014/04/Digital-Board-2.png [content] => Welcome to WordPress. This is your first post. Edit or delete it, then start blogging! Jeg elsker kage [time] => April 17, 2014 5:32 pm ) ) )
The decode code:
$json_string = 'http://95.85.11.40/wordpress/?page_id=20';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
print_r($obj);
If you don't want those array[0] bits, then don't create a 2D array:
$data[] = (array('item' => $post_data));
Should then be:
$data[] = $post_data;
Your current statement read as _add to array $data an array, with 1 key: "item", whereas my version just says: add to $data the value of $post_data.
loping oiver decoded data:
$data = json_decode(file_get_contents($jsonFile), true);
foreach ($data as $idx => $item)
{
echo 'This is item number ', $idx +1, PHP_EOL;
print_r($item);
}
Related
I'm trying to write to a variable inside an object and I can't find how to do it.
Array
(
[0] => stdClass Object
(
[id] => 3
[rota_name] => Tea and coffee
[rota_owner_name] => 9
[rota_notes] =>
[rota_entry] => {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}
[rota_advance_email_days] =>
[rota_reminder_sent] =>
)
I want to change person 8 to person 9
So I think that I need to get the rota_entry (using foreach) and then use Json_decode to get an array and then something but my brain now hurts :( I and don't know how to reset it back up to put into the database again.
I can find lots that talks about simple JSON decode or simple array parsing but not something to help with this
This code assumes $obj = the first entry in your array you show.
So $obj = Array[0]
$json = json_decode($obj->rota_entry);
$json->rota_entry0->person = 9;
$obj->rota_entry = json_encode($json);
This code changes rota_entry0 person 8 to 9
// Your original array
$array = [
0 => (object) [
'id' => 3,
'rota_name' => 'Tea and coffee',
'rota_owner_name' => 9,
'rota_notes' => '',
'rota_entry' =>' {"rota_entry0":{"person":"8","rota_assignment_date":"2018-04-01 20:17:48","rota_role":""},"rota_entry1":{"person":"7","rota_assignment_date":"2018-04-08 20:17:48","rota_role":""},"rota_entry2":{"person":"11","rota_assignment_date":"2018-04-15 20:17:48","rota_role":""},"rota_entry3":{"person":"7","rota_assignment_date":"2018-04-22 20:17:48","rota_role":""},"rota_entry4":{"person":"10","rota_assignment_date":"2018-04-29 20:17:48","rota_role":""},"rota_entry5":{"person":"3","rota_assignment_date":"2018-05-06 20:18:20","rota_role":""},"rota_entry6":{"person":"11","rota_assignment_date":"2018-05-13 20:18:23","rota_role":""}}',
'rota_advance_email_days' => '',
'rota_reminder_sent' => '',
]
];
// Create an empty object to replace the rota_entry key in the array
$rotaEntry = (object) [];
// Iterate through the original rota_entry and replace "person"
foreach (json_decode($array[0]->rota_entry) as $key => $value) {
// You can set whatever logic you want here
// For example: if ($key == "rota_entry4") {$value->person = 4;}
// I'm hardcoding "9"
$value->person = 9;
$rotaEntry->$key = $value;
}
// Assign the newly created (and modified) rotaEntry back to the original array
$array[0]->rota_entry = $rotaEntry;
Try this:
$array = (array) $object;
foreach($array as &$value){
$json = json_encode($value['rota_entry']);
$json -> rota_entry0 -> person = 9;
$value['rota_entry'] = json_encode($json);
}
$array = (object) $array;
good luck.
I wanted to print the name of the coin (obtained from a JSON response of a site) + "test" when the page is loaded; the problem is that only "test" is printed as if it did not find the name of the coin.
PHP code:
<?php
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
find();
function find(){
$coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
$coin = json_decode($coin, TRUE);
$v = $coin['name']."test";
echo $v;
}
?>
JSON structure:
[
{
id: "bitcoin-cash",
name: "Bitcoin Cash",
symbol: "BCH",
rank: "4",
price_usd: "1042.72",
price_btc: "0.114721",
24h_volume_usd: "462221000.0",
market_cap_usd: "17742232718.0",
available_supply: "17015338.0",
total_supply: "17015338.0",
max_supply: "21000000.0",
percent_change_1h: "1.59",
percent_change_24h: "-4.49",
percent_change_7d: "-14.31",
last_updated: "1520950752"
}
]
If I try like this I got the answer. I've printed the $coin for your clear understanding How can you easily access 2D array with its index 0 here.
function find()
{
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
$coin = file_get_contents($coinbase.$array[1]);
$coin = json_decode($coin, TRUE);
//printing only for debug purpose
print '<pre>';
print_r($coin);
print '<pre>';
$v = $coin[0]['name']."test";
echo $v;
}
find();
Output:
Printing it just for your clear understanding why I used $coin[0]['name'] index to get the name from 2D $coin array.
Array
(
[0] => Array
(
[id] => ethereum
[name] => Ethereum
[symbol] => ETH
[rank] => 2
[price_usd] => 687.193
[price_btc] => 0.0760364
[24h_volume_usd] => 1696390000.0
[market_cap_usd] => 67457446384.0
[available_supply] => 98163757.0
[total_supply] => 98163757.0
[max_supply] =>
[percent_change_1h] => -0.63
[percent_change_24h] => -2.36
[percent_change_7d] => -16.98
[last_updated] => 1520955853
)
)
This is what you want
Ethereumtest
N.B: Please note here the comment of https://stackoverflow.com/users/4265352/axiac carefully
$array is not accessible in function find(). Read about variable scope
in PHP then forget everything about $GLOBALS or global
As per comment:
$coinbase = "https://api.coinmarketcap.com/v1/ticker";
$array = array("/bitcoin","/ethereum");
function find(){
global $coinbase;
global $array;
$coin = file_get_contents($coinbase.$array[1]);
$coin = json_decode($coin, TRUE);
print '<pre>';
print_r($coin);
$v = $coin[0]['name']."test";
echo $v;
}
find();
Try:
$coin = file_get_contents($GLOBALS["coinbase"].$array[1]);
$coin = json_decode($coin, TRUE);
$v = $coin[0]['name']."test";
echo $v;
This json is an array of ojects so you should access first the index of the array and then, the property of the object.
EDIT
$coin = file_get_contents("https://api.coinmarketcap.com/v1/ticker/ethereum");
Try to hardcode the url to test it.
I know there may be sources for this out there but I'v tried everything and I'm still not getting the proper solution. That why I'm asking for you help out here.
I have a $_POST array and I want to put values in a an array. Here is the final out I want:
$response = [
['category' => 2, 'value' => "june"],
['category' => 5, 'value' => "may"],
['category' => 8, 'value' => "april"]
]
Here is the catch,the $_POST contains a value of an integer with a space in between and then a string eg '2 june', '5 may' etc
When I get this value, I split it using explode then I try to add the individual values into the response array. This is only adding just one result.
What I tried:
$response = [];
foreach ($_POST as $key => $value) {
$split = explode(" ", $value);
$result = ['category' => $split[0], 'value' => $split[1]];
$response[] = $result;
}
for some reason, the results are not as suggested above. Any ideas and suggestion will be appreciated.
Basically, problem is in the $_POST. This is global array with submitted key-values data. You should NOT use
foreach ($_POST as $key => $value) {
for parsing your data without any checks. This data is submitted by user, and not always they will have format you're waiting for.
For example, if you have a variable "dates" in your HTML form, you should be ready that $_POST['dates'] will be an array of all of your '5 june', '7 july', etc. Don't forget to check and validate all user data you received. It's important by security reason too.
Your code (foreach body, without condition) is ok, I've checked it. Try to set print_r() before explode() you will see that your're working with an array, not with a string.
Your question doesn't have an issue with processing the data into the correct resulting array. The onus falls on $_POST not holding the expected data.
All answers to this question are powerless to fix your $_POST data because no html form was supplied with your question. The only potential value that can be offered is to refine your array building process.
Here are two methods that improve your process by reducing the number of declared variables:
Demonstration uses $a=array('2 june','5 may','8 april'); to represent your $_POST array.
One-liner in a foreach loop:
foreach($a as $v){
$r[]=array_combine(["category","value"],explode(" ",$v));
}
One-liner with no loop:
$r=array_map(function($v){return array_combine(["category","value"],explode(" ",$v));},$a);
Using either process the resulting $r will be:
array (
0 =>
array (
'category' => '2',
'value' => 'june',
),
1 =>
array (
'category' => '5',
'value' => 'may',
),
2 =>
array (
'category' => '8',
'value' => 'april',
),
)
References for used functions:
explode() , array_combine() , array_map()
Try this one:
$response = [];
// just for example use this one
$data = "2 june, 5 may, 7 july";
$temp = explode(",", $data);
// and you can use this one for your case
/*$data = $_POST['var_name']; // var_name is your variable name from $_POST
$temp = explode(",", $data);*/
foreach ($temp as $key => $value) {
$split = explode(" ", trim($value));
foreach ($split as $val) {
$result = ['category' => $split[0], 'value' => $split[1]];
}
$respon[] = $result;
}
echo "<pre>";
echo print_r($respon);
echo "</pre";
the output:
Array
(
[0] => Array
(
[category] => 2
[value] => june
)
[1] => Array
(
[category] => 5
[value] => may
)
[2] => Array
(
[category] => 7
[value] => july
)
)
$response = array();
foreach ($_POST as $key => $value) {
$split = '';
$split = explode(" ", $value);
$result = array('category' => $split[0], 'value' => $split[1]);
$response[] = $result;
}
This is the code I have and I am trying to get and encode the image contents as base64 but I keep ending up with the URL as a base64 string.
In the end I get images as an array from a API I need to transcode them to Base64 to store in a local DB.
This is based on the Gravity Forms API, Wordpress, PHP, mySQL, (LAMP) etc.
<?php
$images = array();
$body = array();
$imagesDecoded = array();
$imgUrls = array(
'1' => 'bg.jpg',
'2' => 'meeting.jpg',
'3' => 'testimonial.jpg',
'4' => 'works.jpg',
);
$imgUrls = array_map(function($el) {
return 'http://orlandojoes.co.uk/rimos/images/' . $el;
}, $imgUrls);
print'<pre>';
print_r($imgUrls);
print'</pre>';
foreach ($imgUrls as $image) {
$data = file_get_contents($imgUrls);
$data = base64_encode($imgUrls);
array_push($body, $data);
}
print '<pre>';
print_r ($body);
print '<pre>';
foreach ($body as $bodyimage) {
$dataDec = base64_decode($bodyimage);
array_push($imagesDecoded, $dataDec);
}
print '<pre>';
print_r ($imagesDecoded);
print '<pre>';
This is the output from when I run this code now:
Array
(
[ptSignature] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[pSignature] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[witness1Signature] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[witness2Signature] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
Array
(
[0] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9iZy5qcGc=
[1] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy9tZWV0aW5nLmpwZw==
[2] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy90ZXN0aW1vbmlhbC5qcGc=
[3] => aHR0cDovL29ybGFuZG9qb2VzLmNvLnVrL3JpbW9zL2ltYWdlcy93b3Jrcy5qcGc=
)
Array
(
[0] => http://orlandojoes.co.uk/rimos/images/bg.jpg
[1] => http://orlandojoes.co.uk/rimos/images/meeting.jpg
[2] => http://orlandojoes.co.uk/rimos/images/testimonial.jpg
[3] => http://orlandojoes.co.uk/rimos/images/works.jpg
)
You have two bugs in your code.
$data = file_get_contents($imgUrls); // This is an array of URLs
$data = base64_encode($imgUrls); // You encode the URLs here!
Should be:
$data = file_get_contents($image); // $image instead of $imgUrls
$data = base64_encode($data); // $data instead of $imgUrls
Or simply:
$data = base64_encode(file_get_contents($image));
Side note, you don't need array_push() in your code, it's typically only needed if you want to push more than one item at one time. So, you can change it to just:
$body[] = $data;
I have the customer details in the following format
How do i fetch the customer id is '5' from the output.
json_decode(array)
Result:
stdClass Object (
[5] => stdClass Object (
[email] => siddareddy.vishnuvardhanreddy#gmail.com
[firstname] => vishnu
[lastname] => siddareddy
)
)
You can cast it to an array and then get the first key:
$key = key( (array) $result_object );
$array = json_decode($json, true);
foreach ($array as $key => $value)
{
echo $key; //or use $value array to get the rest of its info
}
Please note that your first line cannot yield the second line as output. The first line should return an array, while the second code block is an object.
You can loop through all keys and values of your Array/Object and get the '5' that way:
foreach( $decodedjson as $key => $val ) {
#Key is: 5
echo "Key is: {$key}";
#Val['firstname'] is: vishnu
echo "Val['firstname'] is: {$val['firstname']}";
}
You can access the numeric property like this
<?php
$data = array(
"5" => array(
'email' => 'siddareddy.vishnuvardhanreddy#gmail.com',
'firstname' => 'vishnu',
'lastname' => 'siddareddy'
)
);
$json = json_encode($data);
$obj = json_decode($json);
var_dump($obj->{5}->email);
$obj->{5}->email, this the trick.
If you want to invert the array from id to that array from say, email to id:
$result = json_decode($array, true);
// Change email to something else if you want another key
$inversecopy = array_flip(array_map(function($val) { return $val['email']; }, $result));
Example in phpfiddle