Calling many Variables stored in outside file - php

The code I had help with the last couple weeks works great. The problem is it's creating way more needed includes and external files than I first thought and getting to be a challenge to keep track of.
I was told to use MySQL. That would be fine if the data was going to be used over again. The data is only used long enough to build the pages, print to pdf and then it's no longer needed and the files are deleted.
I have three templates that are used to create all the needed pages. Only the data is different but never the same to allow it to be saved beyond it's use.
The problem I started having is when 30+ pages are loaded into a single browser window so it can get processed to pdf, this is calling a few hundred includes and some are being missed. When each page is called by itself it all loads fine.
The other thing I can think of is to try and get the variables belonging to each page in it's own single file and have the page access that file. When I call the file with include "file.php"; it just prints everything to the screen and not where they are needed. That way each file would have 10 - 15 variables in it for each page This would eliminate over 400 external files down to 1+ images for each page.
Is putting them all in one separate file and then called possible?
I hope I explained this correctly.
Thanks in advance.
// What I would like in one file.
$item1 = "Data for Item one";
$photo1 = "img src string to image for item 1";
etc...
$item12 = "Data for Item 12";
$photo12 = "img src string to image for item 12";
This would then call the items in the proper location of the page.
echo "$item1";
echo "photo1";
etc...
echo "$item12";
echo "photo12";

You can use a MySQL database to store information like that. (Settings, etc.)
But you can also use arrays for this which is probably more advisable.
Solution with arrays
An array gives you the possibility to easily store and manage data of a similar type.
You create a new array like this:
$settings = array();
To store a value in it, you have several options:
name it as an integer (0, 1, 2, 3 etc.)
name it as a string ('item1', 'path2' etc.)
$settings = array('path1', 'path2');
This just stored 0 => 'path1' and 1 => 'path1'
To get the value of a key in an array:
echo $settings[0]; //or $settings{0}, outputs 'path1'
echo $settings[1]; //outputs 'path2'
Or you store it as a string:
$settings = array('picture1' => 'path1', 'picture2' => 'path2');
echo $settings['picture1']; //outputs 'path1'
Also, multidimensional arrays are possible:
$settings = array(
'paths' => array(
'picture1' => 'path1',
'picture2' => 'path2'
),
'language' => 'english'
);
You get a value of a multidimensional array like this:
//for every dimension a new [], outputs 'path1'
echo $settings['paths']['picture1'];
Then you can just easily store all your settings and require_once 'settings.php';.
If you want to learn more about arrays, go to the php.net documentation.
Example:
/php/settings.php
$settings = array(
'items' => array(
'item1' => 'Data for Item1',
'item12' => 'Data for Item12',
),
'photos' => array(
'photo1' => 'img src string to image for item 1',
'photo12' => 'img src string to image for item 12',
),
);
index.php
<?php
require_once '/php/settings.php';
echo $settings['items']['item1']; //outputs 'Data for Item1'
//Or you can even use a foreach loop
foreach($settings['items'] as $key) {
echo $key;
echo '<br>';
}
That prints out:
Data for Item1
Data for Item12
Hope this helped.

Related

Associative array of arrays

Ive come upon the following code and having trouble deciphering its use.
(changed up the variable names a bit for simplicity)
$fooo = array(
'dog' => array('pages', 'home'),
'cat' => array('users', 'login'),
'bird' => array('users', 'reset', 1),
);
I am familiar with associative arrays but have not seen this "nested array" implementation before.
Is this code creating an array of arrays?
For example, $fooo['dog'] returns an array where $dog[0]='pages' and $dog[1]='home'
That seems wrong.
Yes, this is an array of arrays. But it perhaps may be more accurate to describe it as an associative array with an indexed array for every value.
The following can be done with it:
$fooo['dog'] // gets array("pages", "home")
$fooo['bird'][0] // gets "users"
$fooo['cat'][1] // gets "login"
$fooo['cow'] = array('x', 'y'); // adds another value to the outer array
$fooo['bird'][] = 2; // $fooo['bird'] now equals array('users', 'reset', 1, 2)
There is nothing wrong with this code, but your example is lacking practicality. There is plenty of code that uses such structures though. For example, a logical representation of a menu with sub-menus on a website (which seems like the source of your sample), this data structure can then be looped to generate an HTML/CSS menu.

Php imploding array then making separated strings

Fairly new to php scene and this is giving me headache.
So I am doing api call (twitch.tv) and I want to get preview links, there are 3 different links, that end with .jpg. Now problem is its stored as array and I need to break it into strings.
I have tried
$preview = $json_array['stream']['preview'];
$foo = implode(",",$preview);
echo $foo;
$foo prints out http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-80x50.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-320x200.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-640x400.jpg,http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-{width}x{height}.jpg
now, how do I go about joining those characters into string, so I can be able to display image.
You should not join your array at all. In your example $json_array['stream']['preview']; is the following:
array(
'small' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-80x50.jpg',
'medium' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-320x200.jpg',
'large' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-640x400.jpg',
'template' => 'http://static-cdn.jtvnw.net/previews-ttv/live_user_adam_ak-{width}x{height}.jpg'
);
So you can use either one of the provided images:
$json_array['stream']['preview']['small']
$json_array['stream']['preview']['medium']
$json_array['stream']['preview']['large']
If none of the images fit your desired resolution you can use the template:
echo str_replace("{width}", $width, str_replace("{height}", $height,"Hello world!"));
In joining the array in to a string you wont have a link for an image, you will have 3 links joined together. Use;
$json_array['stream']['preview'][0]
and change the 0 for which of the images you want.

Multiple Keys to an array in if/else search

My code is pretty basic. I'm using an array to generate a datasheet for a product based on it's SKU and a filepath.
My array looks like this:
$a=array(
"/images/ManualSheets/factSheetCLASSIC.pdf"=>"KE800/6",
"/images/ManualSheets/factSheetMICRO.pdf"=>"KE800/12",
"/images/ManualSheets/factSheetSMALL.pdf"=>"KE4000/12",
"/images/ManualSheets/factSheetMEDIUM.pdf"=>"KE8000/12",
);
Where the first Key is the filepath, and the second Key is the SKU (as generated by the system) I then use an if/else to generate a button - so if a product is not in the array it returns a blank value and doesn't have a button which leads to nowhere
$factsheetweblink_url = array_search($product_sku,$a);
if ($factsheetweblink_url==false) {
echo " ";
}
else {
echo "<div class='productpagestockistBTN'>
<img src='/images/FactSheet_btn.png' >
</div>";
}
?>
This code works fine. The catch comes when I have products with different SKUs but the same datasheet file, (same brand and make but a different model). Currently I can only get it to work by uploading multiple copies of the datasheets with different names, but it's becoming a big waste of space.
I have tried using an array as a key to hold multiple values to the one key..
"/images/ManualSheets/factSheetMEDIUM.pdf"=> array("KE8000/12","KE7000/12"),
but it doesn't seem to be working... I'm not quite sure if I need to refine my if statement to search within the sub arrays as well or..?
Any help would be appreciated, thanks in advance.
You should use arrays like this:
$products = array(
0 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC.pdf",
"skus" => array("KE800/6","KE900/6")
),
1 => array(
"pdf" => "/images/ManualSheets/factSheetCLASSIC3.pdf",
"skus" => array("KE100/6","KE200/6"))
);
This is because array_search returns just first row whit that key.
Then just do your own search function like:
function findBySku($items, $sku) {
$pdf = ""; // return empty if not found.
foreach($items as $row) {
if (in_array($sku, $row['skus'])) {
$pdf = $row['pdf'];
break;
}
}
return $pdf;
}
and call that function:
$pdf = findBySku($products, "some sku");

Return Different PHP Array Values Based on A User ID-Related Constant

I am working with an array of tokens for an HTML template. Two of them ('{SYS_MENU}' and '{SUB_MENU}') are used to generate control buttons for the web application. Right now the buttons show up on the login page before the user's credential's are validated, and I need to change the code so that the buttons are hidden until after users login and reach the main menu. When someone types the http: address into their browser and arrives at the login page the system starts a session for them in the MySQL sessions table with USER_ID = 0. After they login the USER_ID changes to whatever number was assigned to them at initial registration (Example: USER_ID = 54), and after they logout at the end of the session back to 0. Tying this constant to the buttons seems like the best solution and I have found it to work in the past under similar circumstances.
Here is the original array:
$template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => theme_main_menu('sys_menu'),
'{SUB_MENU}' => theme_main_menu('sub_menu'),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
The first thing I did was to work with the references directly in the HTML template. I saw an example on w3schools that made it look like you could just type a PHP script into HTML and have it resolve. That didn't do anything except echo a bunch of text randomly into the page. I then found another citation that said you had to activate the PHP with an .HTACCESS entry before it would work directly in HTML. But that didn't close the deal either.
I know that changing '{SYS_MENU}' and '{SUB_MENU}' values in the array to => "", produces the results that I want (I.E. make the menu buttons disappear). So my next thought was I'll create an IF statement that returns two versions of the array based on circumstances, something like:
if(USER_ID != 0)
{
return $template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
return $template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}
But all that did was cause the application load to terminate at a white screen with no error feedback.
My most recent attempt came from something I read here on Stack Overflow. I know that you cannot put IF statements into an array. But the article at this link described a workaround:
If statement within an array declaration ...is that possible?
So I rewrote the array as follows:
template_vars = array(
'{LANG_DIR}' => $lang_text_dir,
'{TITLE}' => theme_page_title($section),
'{CHARSET}' => $charset,
'{META}' => $meta,
'{GAL_NAME}' => $CONFIG['gallery_name'],
'{GAL_DESCRIPTION}' => $CONFIG['gallery_description'],
'{SYS_MENU}' => ('USER_ID != 0' ? theme_main_menu('sys_menu') : ""),
'{SUB_MENU}' => ('USER_ID != 0' ? theme_main_menu('sub_menu') : ""),
'{ADMIN_MENU}' => theme_admin_mode_menu(),
'{CUSTOM_HEADER}' => $custom_header,
'{JAVASCRIPT}' => theme_javascript_head(),
'{MESSAGE_BLOCK}' => theme_display_message_block(),
);
But that seems to have no effect at all. The application doesn't crash but the buttons are static whether you are logged in or logged out.
My question is: What am I missing? I can see that this is possible. But I've been trying things for a day and a half and just seem to be dancing around the solution. Your thoughts would be greatly appreciated.
The problem here is that you are calling return. With a global include file like this there is not context to return to so the application terminates. What you want to do is just assign the variables.
if(USER_ID != 0)
{
$template_vars = //FIRST VERSION OF ARRAY WITH FULL VALUES//
}
else
{
$template_vars = //SECOND VERSION OF ARRAY WITH ONLY => ""//
}

Can PHP Array Keys have an Alias?

This is just a curious question, the reasoning behind it is purely to be slightly more lazy on my part. Here is what I mean..
Say I have a website, where htaccess makes nice urls, and sends that data to the $_GET['p'] array key as the current 'page'. In the index file, I setup the page, and the first thing I do is setup some page settings in a config file, $_PAGE array. Now, say I have multiple pages I want to have the same settings, (and down in the page, other things may slightly change that do not correspond to the settings. So currently, I have something that looks like the following 2 php files.
// index.php
include('page.array.php');
echo '<title>'.$_PAGE[$_GET['p']]['title'].'</title>';
// page.array.php
$_PAGE = array(
'some/page/' => array(
'title' => 'This is an example'
)
)
$_PAGE['some/aliased/page/'] = $_PAGE['some/page/'];
Notice that at the end ofthe page array, in order to 'alias' a page I must add this to the end after the array has been created.
Is there any method in php that maybe I am just unaware of, that could make me a tad bit lazier (and at the same time add to cleaner code), and make it so I can simply alias the key? I notice the following doesn't work, and I suppose my question is, is there any way to create the alias within the same array during the creation of the array?
This example deosn't work:
// page.array.php
$_PAGE = array(
'some/page/' => array(
'title' => 'This is an example'
),
'some/aliased/page/' => $_PAGE['some/page/']
)
Maybe a way to refer to "this" array, from within itself?
If this is not possible, I don't have an issue with the "Not Possible" answer. Though if you have a better method of solving this, other then the way I have described above, in the sake of being lazier, I would be interested in reading it :)
I don't believe you can have array values that mirror other values in the array like this. The first thing that comes to mind though would be for you to construct your $_PAGE array from within a switch statement, using fall-through values as aliases:
// Define path for testing, and empty page array
$path = "some/aliased/page";
$page = Array();
// Time to evaluate our path
switch ($path) {
// If it's either of these two cases
case "some/page":
case "some/aliased/page":
// Assign this array to $page
$page = Array("Title" => "Two Paths, One Page.");
break;
// If it's this case
case "some/other/path":
// Assign this array to $page
$page = Array("Title" => "Something else.");
break;
// If the path isn't found, default data
default:
$page = Array("Title" => "Page not found");
}
// Output the result
var_dump($page);
Execute it: http://sandbox.onlinephpfunctions...ebd3dee1f37c5612c25
It's possible:
$_PAGE = array('some/page/' => array('title' => 'This is an example'));
$_PAGE['some/aliased/page/'] = &$_PAGE['some/page/'];
$_PAGE['some/page/'] = 7;
var_dump($_PAGE);
Use the & to get a reference to a (non-object) variable instead of its value.

Categories