Echo specified array content - php

I have a JSON file which iam using ( file_get_contents ) from a url, to extract the values to a good formatted way. The problem is that i need to echo out a specific value content but failed to do that. So here is the piece of code iam providing here may be if someone would like to help me out to do it.
Array
(
[type] => result
[data] => Array
(
[0] => Array
(
[title] => My Radio Name
[song] => Artist Name - Song Name
[track] => Array
(
[artist] => Artist Name
[title] => Song Name
[album] => Unknown
[royaltytrackid] => 0
[id] => 542
[playlist] => Array
(
[id] => 45
[title] => ALL SONGS
)
.....
SO i need to echo out [artist] AND [title] Which will be echoed as:
Artist Name | Song Name
Thanks in advance any help would be appreciated :)

Depends on format of your json but below code should work:
foreach ( $json['data'] as $entry ){
foreach ( $entry['track'] as $track ){
echo $track['artist'] ." | ". $track['title'] ."<br/>";
}
}

Related

php push an array into an existing array by it's index

I'm having trouble with putting this question to words so ill just use a simple example, hope the title sortof got my problem across.
I'm creating a blog site where I can create blogposts and people can post comments. This is all saved in JSON except for login details which are saved in MySQL.
Now saving the blogposts go fine but I'm now trying to save comments.
Lets say the blogpost array looks like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
Now someone writes a comment on 'second blogpost', I save it into an array like this(user taken from MySQL):
Array
(
[user] => myusername
[comment] => first post was better!
)
Now I want to merge them like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
[comments] => Array
(
[user] => myusername
[comment] => first post was better!
)
)
)
I tried searching for a while and I'd expect this to be somewhere on the site already but I can't find it. I tried a couple variations of array_push and array_merge but it always ended up replacing the relevant blogpost instead of adding onto it.
EDIT: Someone noted the new array can't just float around, I think it's better now.
If you had any related key between posts and comments ( like having post_id in comment array ) that would make more sense to merge/put them.
I assume that's your blogpost
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
And your comments should be like:
Array
(
[user] => myusername
[comment] => first post was better!
[post_id] => 1
)
That way, you would be able to find the matched blogpost.
But, outside of your data structure, here is an example to merge an item into an element of an array of array.
A nested loop example.
foreach($posts as &$post){
foreach($comments as $comment){
if($post['id'] == $comment['post_id']){
$post['comments'][] = $comment;
}
}
}
the key here is sending each reference of the element into loop by &$post and then just manipulate them in loop.
Working with indexed arrays. (Like you already have index names as post_id and a comments index as an empty array)
foreach($comments as $comment){
$posts[$comment['post_id']]['comments'][] = $comment;
}
When the blogpost is updated, I assume you can get the id of that blogpost.
Then you can check if your data structure already has a key "comments". If it does not, add the key and create an array containing the comment and the user as the first array.
If it already exists, add a new array with the user and the comment so that there can be multiple comments for each blogpost.
For example using array_map:
$blogPosts = array_map(function ($blogPost) use ($blogPostId, $comment) {
if ($blogPost["id"] === $blogPostId) {
isset($blogPost["comments"]) ? $blogPost["comments"][] = $comment : $blogPost["comments"] = [$comment];
return $blogPost;
}
return $blogPost;
}, $blogPosts);
Php demo
So I fixed it after a bit of thinking
This is the final structure:
Array
(
[0] => Array
(
[id] => 0
[title] => 1st post
[content] => 1st post works!
[date] => 21-01-2019
[comments] => Array
(
[0] => Array
(
[user] => Me
[comment] => hey 1
[date] => 12:02 21-01-2019
)
[1] => Array
(
[user] => Me
[comment] => hey 2
[date] => 12:03 21-01-2019
)
)
)
)
I added a timestamp because of a suggestion here. It's also a simplified version of what I actually use, I tried adding many more comments and on multiple posts which both work.
This is the code, I should mention the ID is in the URL and it's saved as JSON:
$filename = file.json;
$currentArray = json_decode(file_get_contents($filename), true);
$comment = $_POST['comment'];
$username = $_SESSION['username'];
$date = date("H:i d-m-Y");
$id = $_GET['id'];
Pretty straightforward so far, here is how the array is created:
$currentArray[$id]["comments"][] = array (
'user' => $username,
'comment' => $comment,
'date' => $date
);
[$id] saves it to the correct post, ["comments"] saves it to the comments key(or creates it) and the last [] gives every comment a different index inside the ["comments"].
$newJSON = json_encode($currentArray, JSON_PRETTY_PRINT);
file_put_contents($filename, $newJSON);
And lastly encoding it and saving it to JSON.
Hope this helps someone.

Get data from OMDb API with xml

I'l try to get the movie title and info from the omdb API. This is my code:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
if($xml) {
echo "<h2>" .$xml->title. "</h2>";
}
else
{
echo "Nothing found. Add the info manualy";
}
?>
The "enter" value is from the search form with AJAX. He create only an empty h2 tag. How can i get also the data from the API?
Thank you,
Julian
You should familiarize yourself with the structure of the xml to know how to access its elements. print_r(get_object_vars($xml)) will show you a structure like this:
Array
(
[#attributes] => Array
(
[totalResults] => 3651
[response] => True
)
[result] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => World War Z
[year] => 2013
[imdbID] => tt0816711
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0NTgxMjIxOF5BMl5BanBnXkFtZTcwMDM0MDY1OQ##._V1_SX300.jpg
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => Captain America: Civil War
[year] => 2016
[imdbID] => tt3498820
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMjQ0MTgyNjAxMV5BMl5BanBnXkFtZTgwNjUzMDkyODE#._V1_SX300.jpg
)
)
...
...
...
[9] => SimpleXMLElement Object
(
[#attributes] => Array
(
[title] => War
[year] => 2007
[imdbID] => tt0499556
[type] => movie
[poster] => https://images-na.ssl-images-amazon.com/images/M/MV5BMTgzNTA4MTc3OF5BMl5BanBnXkFtZTcwOTA0ODk0MQ##._V1_SX300.jpg
)
)
)
)
So you receive an array with results where you need to pick from. Alternatively if you know the exact title the API has the t=title option which only returns a single result (see documentation).
So assuming you use the s=title option which returns multiple results, you can use something like this to pick information from the first result:
<?php
$enter = $_GET["enter"];
$content = file_get_contents("https://www.omdbapi.com/?s=$enter&r=xml");
$xml = simplexml_load_string($content);
# show the structure of the xml
# print_r(get_object_vars($xml));
if($xml) {
print "<h2>" .$xml->result[0]['title']. "</h2>";
print "<br>imdbID=" . $xml->result[0]['imdbID'] ;
} else {
echo "Nothing found. Add the info manualy";
}
?>

Print array value PHP

I'm having a little problem when trying to print certain values from my database. OK so I have a table in my database called site_details where I save the site name, phone and email. I have a query that returns the following array:
Array
(
[0] => Array
(
[text] => My Store
[0] => My Store
[column_key] => site_name
[1] => site_name
)
[1] => Array
(
[text] => (123) 456 7890
[0] => (123) 456 7890
[column_key] => site_phone
[1] => site_phone
)
[2] => Array
(
[text] => email#yahoo.com
[0] => email#yahoo.com
[column_key] => site_email
[1] => site_email
)
)
I would like to print out the site details using the following code:
//Print out site name
//$site_details is the array being returned from the database
<?php echo $site_details['site_name']; ?>
This returns an
Undefined index: site_name error
. Anyone know how I could go about this? Any help is greatly appreciated.
Update
Here's the code i use to return the site details:
Funtions.php
public function getSiteDetails(){
global $pdo;
$getDetails = $pdo->prepare("
SELECT *
FROM site_details
");
$getDetails->execute();
return $getDetails->fetchAll();
}
This is where I call the function:
index.php
require 'res/php/Functions.php';
$obj = new Functions();
//Get site details
$site_details = $obj->getSiteDetails();
Database image:
For your given array the printing mechanism is as follows:-
<?php
foreach($site_details as $site_detail){
echo $site_detail['column_key'].' is:- '.$site_detail['text'];
}
?>
Note:- fetch_assoc will be better objective.
Also every column value comes separately which shows you did something extra in your code, which is actually not needed
for each value to print:-
<?php echo $site_details[0]['text']; ?>
Use $getDetails>fetch(PDO::FETCH_ASSOC) that gives an array like,
Array
(
[0] => Array
(
[text] => My Store
[column_key] => site_name
)
[1] => Array
(
[text] => (123) 456 7890
[column_key] => site_phone
)
[2] => Array
(
[text] => email#y
[column_key] => site_email
)
)
Then use,
echo $site_details['column_key'];

Getting array value

My debugging output below
Array (
[0] => Array (
[re_text_field_id] => No posts to display
[re_textarea_field_id] => boring jokes
[re_image_field_id] => Array (
[id] => 6
[src] => http://localhost/project/wp-content/uploads/2014/02/bg1.gif
)
) [1] => Array (
[re_text_field_id] => fuck it
[re_textarea_field_id] => I feel dumb for asking, but how on earth would i go about using the repeatable fields in a way which outputs the fields needed
[re_image_field_id] => Array (
[id] => 4 [src] => http://localhost/project/wp-content/uploads/2014/02/bg-gradient1.png
)
)
)
To get text field I used
$options = get_option('demo_options')
$slides = $options['re_'];
foreach ($slides as $slide) {
echo $slide['re_textarea_field_id'];
}
But I am unable to get image path somewhat like this way
echo $slide['re_image _field_id'];
Try this, to retrive the path of the image. Need to add ['src']
echo $slide['re_image_field_id']['src'];

PHP Multidimensional Array of Objects

Can anyone help me with this little problem please? I need to get (echo) the name, id and link from an array but after hours trying I have not been able, see the array below... Thank you in advanced.
Array
(
[campaigns] => Array
(
[0] => Campaign Object
(
[name] => My name 1
[id] => 123456789012
[link] => 123456789012
)
[1] => Campaign Object
(
[name] => My name 2
[id] => 123456789012
[link] => 123456789012
)
[2] => Campaign Object
(
[name] => My name 3
[id] => 123456789012
[link] => 123456789012
)
)
)
If you know which campaign you want, you can get it like this:
echo($data['campaigns'][0]->name);
echo($data['campaigns'][0]->id);
echo($data['campaigns'][0]->link);
If you want to loop through all of them, you could do something like this:
foreach ($data['campaigns'] as $item) {
echo($item->name . "\n");
echo($item->id . "\n");
echo($item->link . "\n");
}
This is all a bit of a guess because we don't know what the Campaign class actually looks like - there may be a getName() method that you should be using instead of just accessing the name value directly, for example.
foreach ($array['campaigns'] as $key => $value){
echo "Name: ".$value->name." ID: ".$value->id." Link: ".$value->link."\n";
}
Question is a little light on details to debug but have you tried this?
<?php echo $campaigns[0]->name; ?>

Categories