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'];
Related
I stored some data to an array using this code ($rval['arr']):
$id = $this->input->get("id");
$rval['arr'] = $this->General_model->details($id);
When I print my result by using print_r($rval['arr']); it shows like this:
Array ( [0] => Array ( [id] => 54 [name] => Rajib [address] => DumDum [mobile] => 9865321245 [doj] => 21-2-2010 [fare] => 1245 [img_name] => Penguins.jpg ) )
Now I want to store the address value to a variable like add. How can I do this?
Try this....
$address=$rval['arr'][0]['address'];
demo
You can also do it in a foreach() loop:
foreach($rval['arr'] as $array){
echo $array['name'];
echo $array['address'];
echo $array['mobile'];
}
I have been trying to work this out for two days now and am hitting a brick wall. I have a skyscanner array that has flight itineraries where I have the flight
Leg - being Itineraries -> OutboundLegId -
and also the legs which shows the flight number - being
Legs -> FlightNumbers -> FlightNumber.
What I am trying to achieve is to display the Itinerary and then join the Flight Number on to that. But no matter what I try I cannot get this to work. I have read all about Keys on here and tried loads of examples but am coming up with nothing. Can someone point me in the right direction please?
Example arrays below
[Itineraries] => Array
(
[0] => Array
(
[OutboundLegId] => 13542-1610140610-29-0-13445-1610141240
[InboundLegId] => 13445-1610211340-29-0-13542-1610211640
[PricingOptions] => Array
(
[0] => Array
(
[Agents] => Array
(
[0] => 2174187
)
[QuoteAgeInMinutes] => 31
[Price] => 200.98
[DeeplinkUrl] => http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=5JlLCgyPUKY0hT8T0Ybh6dL0Xf0htAiHTFX7RU79eeI3XvrsxvEqP1QUJAoHiHRd&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fUK%2fen-gb%2fGBP%2fcook%2f2%2f13542.13445.2016-10-14%2c13445.13542.2016-10-21%2fair%2fairli%2fflights%3fitinerary%3dflight%7c-32294%7c1152%7c13542%7c2016-10-14T06%3a10%7c13445%7c2016-10-14T12%3a40%2cflight%7c-32294%7c1153%7c13445%7c2016-10-21T13%3a40%7c13542%7c2016-10-21T16%3a40%26carriers%3d-32294%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d200.98%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3d3bc96bda-fd7c-403a-b841-2ccc3c26071d%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-09-29T08%3a18%3a27
)
[Legs] => Array
(
[0] => Array
(
[Id] => 13542-1610140610-29-0-13445-1610141240
[SegmentIds] => Array
(
[0] => 1
)
[OriginStation] => 13542
[DestinationStation] => 13445
[Departure] => 2016-10-14T06:10:00
[Arrival] => 2016-10-14T12:40:00
[Duration] => 270
[JourneyMode] => Flight
[Stops] => Array
(
)
[Carriers] => Array
(
[0] => 105
)
[OperatingCarriers] => Array
(
[0] => 105
)
[Directionality] => Outbound
[FlightNumbers] => Array
(
[0] => Array
(
[FlightNumber] => 1152
[CarrierId] => 105
)
)
)
Assuming this is one big array and its called $data you can nest a couple of foreach loops.
I use foreach loops as I assume there are cases where this data structure get more complex than the one you show
foreach ( $data['Itineraries'] as $itin ) {
foreach ( $data['Legs'] as $legs) {
if ($legs['Id'] == $itin['OutboundLegId']) {
// we matched the itinerary with a leg
echo $legs['OutboundLegId'] . ' ' . $legs['FlightNumbers'][0]['FlightNumber'];
}
}
}
Use it as draft. Can't perform function without feedback.
Put proper arrays instead of {YOUR-ARRAY-WITH-LEGS} and {YOUR-ARRAY-WITH-ITINERARIES}
$sortedLegs = array_column('Id', {YOUR-ARRAY-WITH-LEGS});
$joinedArray = array_map(function($itinerary) use($sortedLegs){
if(array_key_exists($itinerary['OutboundLegId'],$sortedLegs)) {
$itinerary['legs'] = $sortedLegs[$itinerary['OutboundLegId']];
}
return $itinerary;
},{YOUR-ARRAY-WITH-ITINERARIES});
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/>";
}
}
I'm pulling in a list of my vimeo albums using the Vimeo API and the looping three times through the array to get to the albums. It works fine.
My question is, I'm isolating the date, so how can I create a new array and sort it by the date?
While where at it, is there a way to jump to the third level of a multi-dimensional array?
$albums=$vimeo->call('vimeo.albums.getAll', array('user_id' => $myUserId));
$albums_array=object_2_array($albums);
foreach($albums_array as $album_array_two){
foreach($album_array_two as $album_array_three){
foreach($album_array_threeas $album){
if(stristr($album['title'],'conference')){
$title=$album['title'];
$description=$album['description'];
$date=stristr($album['description'],'.',true);
$year_comma=stristr($date,',');
$year=ereg_replace("[^0-9]", "", $year_comma);
$url_title='http://www.psfk.com/events/'.str_replace( " ", "-", strtolower($title));
$url=''.$title.'';
$thumb=$album['thumbnail_video']['thumbnails']['thumbnail'][1]['_content'];
echo '<li class="album">';
echo '<img src="'.$thumb.'" alt="'.$title.'" />';
echo '<div class="info">';
echo '<h2>'.$url.'</h2>';
echo $description.'<br />';
echo 'View...';
echo '</div></li>';
}
}
}
}
Sample of the array returning one item:
Array (
[generated_in] => 0.0828
[stat] => ok
[albums] => Array (
[on_this_page] => 7
[page] => 1
[perpage] => 50
[total] => 7
[album] => Array (
[0] => Array (
[id] => 1690236
[title] => Interviews
[description] =>
[created_on] => 2011-09-10 21:43:49
[total_videos] => 1
[url] => Array (
[0] => http://vimeo.com/album/1690236
)
[video_sort_method] =>
[thumbnail_video] => Array (
[id] => 28825158
[owner] => 718882
[title] => Where Inspiration Comes From [thumbnails] => Array (
[thumbnail] => Array (
[0] => Array (
[height] => 75
[width] => 100
[_content] => http://b.vimeocdn.com/ts/192/593/192593029_100.jpg
)
)
)
)
)
)
)
)
In order to sort by date, you can use the php_function array_multisort(). There is a good example on that page that I think shows what you need. I'll try to provide a better example using your data. Suppose after looping through your albums you end up with an array $myAlbums that looks like this:
Array (
[0] => Array(
[title] => My Title
[description] => some description
[date] 01-05-2011
)
[1] => Array(
.......
)
In order to sort this by date, you could do the following (taken from the example on the php page)
<?php
// Obtain a list of columns
foreach ($myAlbums as $key => $row) {
$date[$key] = $row['date'];
}
// Sort the data with volume descending, edition ascending
// Add $myAlbums as the last parameter, to sort by the common key
array_multisort($date, SORT_DESC, $myAlbums);
?>
Then you can print_r($myAlbums); and you should see that it is sorted. You might have to change the SORT_DESC flag depending on what formate your dates are in. I can't really explain HOW this works, because I'm still trying to figure it out myself... but I think it is what you need.
I've hit a bit of a problem, I'm currently working on a custom CMS that allows the user to change the websites title, description, keywords and footer, as well as various other settings, which are all kept in one mysql table called site_settings which has two columns
setting and content, the setting column holds the settings name, for example title, and the content holds the information such as "welcome to my website", these are loaded into the site by various queries which works great, the trouble im having is I want to load the information into the form fields in the CMS, which I was hoping to do with the following query
$query = mysql_query("SELECT `setting`, `content` FROM `site_settings`");
and then create an array with the information using:
$content = mysql_fetch_array($query);
but the only way to get the information is to make a while statement that cycles through every row until it reaches the end, but what i want to be able to do is use the setting column in my table as the main identifier for retrieving the content
for example at the moment with the while array my arrays look like this:
Array ( [0] => title [1] => title [2] => title [3] => title )
Array ( [0] => keywords [1] => keywords [2] => keywords [3] => keywords )
Array ( [0] => description [1] => description [2] => description [3] => description )
Array ( [0] => footnote [1] => footnote [2] => footnote [3] => footnote )
Array ( [0] => notice_state [1] => notice_state [2] => 1 [3] => 1 )
Array ( [0] => maintenance_state [1] => maintenance_state [2] => 1 [3] => 1 )
Array ( [0] => notice_message [1] => notice_message [2] => notice [3] => notice )
Array ( [0] => maintenance_message [1] => maintenance_message [2] => maintenance [3] => maintenance )
Array ( [0] => about_us [1] => about_us [2] => about us [3] => about us )
Array ( [0] => article_shorten_length [1] => article_shorten_length [2] => 80 [3] => 80 )
so id have to cycle through them all to retrieve all the information, with the following statement:
while($content = mysql_fetch_array($query)) {
echo $content['content'];
}
but what I'm looking to do is put them all into one array with 1 or a few mysql statements like so
Array (
title -> 'welcome to my website',
description -> 'this is my website',
)
etc...
and just echo in the information by calling the setting column from my array without using a while statement and without a separate mysql query for each row like:
$content['title'];
$content['description'];
Is there a way to do this?
Use a loop with mysql_fetch_row:
while ($row = mysql_fetch_row($query))
{
$content[$row[0]] = $row[1];
}
This avoids reading the whole result set into an array that you then discard. It might be more efficient, therefore.
I am really unsure as to what exactly you want. But if I get your question properly, are you looking for the below:
while($content=mysql_fetch_array($query))
$finalResultObj[$content['setting'] ] = $content['content'];
After this, you have an associative array, and (if I have understood your question properly) you would be able to use it like $finalResultObj['setting'] to get the relevant content.
Are you sure, this is what you want?