php - converting swithch to .csv file read method - php

Can someone please point me in the correct direction to convert my switch code from currently being listed like below to being drawn from a CSV file instead:
$video = (isset($_GET['video']) ? $_GET['video'] : null);
if($video) {
switch($video) {
case "apple":
$Heading ='Apple Heading';
$Videonum ='1';
$Content ='<h2>Apple Sub Heading</h2>
<p>Apple content</p>';
$SideContent ='Apple side content';
break;
I will end up with lots of cases and it'll be easier to manage from a .csv file - thank you

I think you need a two-dimensional array with the identifier ('apple', …) as the key for the inner arrays. By parsing a CSV-file you will get an array with multiple rows, but you need to search for the row, that contains the required data. Maybe you also can save PHP files containing the necessary data-arrays or even use a database (which is probably most common for such cases).
Target arrays as I would use it:
$data = array(
'apple' => array(
'heading' => 'Apple Heading',
'video_num' => 1,
'content' => '<h2>Apple Sub Heading</h2>
<p>Apple content</p>',
'side_content' => 'Apple side content',
),
/* more manufacturer sub-arrays */
);
In this first case you could access the whole data by just reading from the array:
if( !empty( $_GET['video'] ) && isset( $data[$_GET['video']] ) )
{
var_dump(
$data[$_GET['video']]['heading'],
$data[$_GET['video']]['content']
);
}
else
{
echo '<p class="error">No video specified or "' . $_GET['video'] . '" is not available.</p>';
}
FYI; Array as retrieved from a CSV-file:
$data = array(
1 => array(
'manufacturer' => 'Apple',
'heading' => 'Apple Heading',
'video_num' => 1,
'content' => '<h2>Apple Sub Heading</h2>
<p>Apple content</p>',
'side_content' => 'Apple side content',
),
/* more rows */
);

Read your csv file
$data = array();
$fp = fopen('manufacturer.csv', 'r');
while (!feof($fp)) {
$line = explode(';',fgets($fp));
$data[$line[0]]['heading'] = $line[1];
$data[$line[0]]['video'] = $line[2];
$data[$line[0]]['content'] = $line[3];
$data[$line[0]]['side'] = $line[4];
}
fclose($fp);
Your csv looks like
apple;Apple Heading;1;<h2>Apple Sub Heading</h2><p>Apple content</p>;Apple side content
microsoft;MS Heading;1;<h2>MS Sub Heading</h2><p>MS content</p>;MS side content
...
Then acces your content with the manufacturer name
if(isset($data[$_GET['video']] && !empty($_GET['video']))){
$Heading = $data[$_GET['video']]['heading'];
$Videonum = $data[$_GET['video']]['video'];
$Content = $data[$_GET['video']]['content'];
$SideContent = $data[$_GET['video']]['side'];
}

Related

How do I compare a string to multiple, but separate, arrays in PHP?

I am trying to write a script that I can implement into WordPress. The purpose of this doesn't really matter.
What I am trying to get is the script to detect the URL, see if any part of the URL contains a string from one of 4 different arrays, and then include the correct file.
This is what I currently have:
<?php
//Detect URL and remove slashes and ".php"
$url = $_SERVER["REQUEST_URI"];
$find = array( '/', '.php');
$clear = array( ' ', ' ');
//Arrays to detect from
$region1 = array( 'LosAngeles', 'SantaMonica', 'Hollywood' );
$region2 = array( 'Houston', 'Dallas' );
$region3 = array( 'Las Vegas', 'SaltLakeCity' );
//Assign a region
if ( in_array( $url, $region1 ) ) {
$region = "California";
}
elseif ( in_array( $url, $region2 ) ) {
$region = "Texas";
}
elseif ( in_array( $url, $region3 ) ) {
$region = "Nevada";
}
//Load file based on region
if ( $region = "California"; ) {
include "file1.php";
}
elseif ( $region = "Texas" ) {
include "file2.php";
}
elseif ( $region = "Nevada" ) {
include "file3.php";
}
?>
I have already tried foreach, but that doesn't let you run a loop for more than 1 array. I am also not trying to do an array_intersect. Just checking that the URL matches at least one of the arrays.
All your guys' help is appreciated!
Thank you!
You already name foreach and array in your question and that points into the right direction.
But first I'd like to point out this variable naming:
//Arrays to detect from
$region1 = array( ... );
$region2 = array( ... );
$region3 = array( ... );
These three variable actually can be easier represented by an array which again makes that variable then compatible with foreach as you can use it to iterate (traverse over) an array:
$regions = [
"California" => [ ... ],
"Texas" => [ ... ],
"Nevada" => [ ... ],
];
foreach ($regions as $region => $cities) {
...
}
Now what you only need is a map from regions to file-names to include:
$files = [
"California" => "file1",
"Texas" => "file2",
...
]
Then you can map it within the foreach easily:
if (!isset($files[$region])) {
throw new UnexpectedValueException(sprintf("File for region %s missing", var_export($region, true))));
}
$file = sprintf("%s.php", $files[$region]);
include($file);
return;
This mini-program will check if there is a file defined for a region and then include it. It's different to your example as it does not use an if clause but just returns if there is a region match. Even though, a matching reason is even expected in the first place.
So you need to wire this within the loop to find that one case that matches the region based on cities:
foreach ($regions as $region => $cities) {
if (!in_array($url, $cities))
continue;
}
if (!isset($files[$region])) {
throw new UnexpectedValueException(
sprintf("File for region %s missing", var_export($region, true)));
}
$file = sprintf("%s.php", $files[$region]);
include($file);
return;
}
throw new UnexpectedValueException(
sprintf("No region found for URL %s", var_export($url, true))
);
Take-aways:
Do not number variables -> nearly always this is a sign you can take an array instead.
If there is one case out of many it's often a single if within a loop.
Arrays in PHP are also a hash-map. You can ask if something exists (e.g. by it's key). Use maps to your benefit.

PHP - Array inside array dynamically

Previous, I have searched in Google. But I don't find what I want...
I want to add 2 array to an array. This is my code :
$labelCollection = array();
$labelArray1 = array("Staff ID", "Photo Profile");
$labelArray2 = array("Religion", "Postcode");
But, I want to make the result like this :
$labelCollection =
array('info_1' => array('Staff ID', 'Photo Profile'),
'info_2' => array('Religion', 'Postcode')
);
Try
<?php
$labelCollection = array();
$labelArray1 = array("Staff ID", "Photo Profile");
$labelArray2 = array("Religion", "Postcode");
$labelCollection = array('info_1' => $labelArray1 ,
'info_2' => $labelArray2
);

How to compute tf-idf from multiple text files in php?

I'm successfully computing tf-idf from an array. Now I want that tf-idf should be computed from multiple text files as I have multiple text files in my directory. Can anyone please modify this code for multiple text files so that first all the files in the directory should read and then on the basis of these files contents tf-idf computed.. Below is my code thanks...
$collection = array(
1 => 'this string is a short string but a good string',
2 => 'this one isn\'t quite like the rest but is here',
3 => 'this is a different short string that\' not as short'
);
$dictionary = array();
$docCount = array();
foreach($collection as $docID => $doc) {
$terms = explode(' ', $doc);
$docCount[$docID] = count($terms);
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('df' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$docID])) {
$dictionary[$term]['df']++;
$dictionary[$term]['postings'][$docID] = array('tf' => 0);
}
$dictionary[$term]['postings'][$docID]['tf']++;
}
}
$temp = ('docCount' => $docCount, 'dictionary' => $dictionary);
Computing tf-idf
$index = $temp;
$docCount = count($index['docCount']);
$entry = $index['dictionary'][$term];
foreach($entry['postings'] as $docID => $postings) {
echo "Document $docID and term $term give TFIDF: " .
($postings['tf'] * log($docCount / $entry['df'], 2));
echo "\n";
}
Have a look at this answer: Reading all file contents from a directory - php
There you find the information how to read all the file contents from a directory.
With this information you should be able to modify your code by yourselve to get it work like expected.

i have an array in an array that contains 3 items, how do I make it go through every item in both arrays?

I am pulling results from an LDAP query with php. One of the items in the array of results is an array with 3 sets of information. How do I make it display all three sets instead of just the first? See my code below:
if ($ds) { $ds=ldap_connect("ldap-server");
$r=ldap_bind($ds);
$sr=ldap_search($ds, "DC=,DC=co,DC=uk",$search);
$info = ldap_get_entries($ds, $sr)or die('get info fail');
$header = array(
t('Picture'),
t('First Name'),
t('Last Name'),
t('Role'),
t('Email')
);
$rows = array();
for ($i=0; $i<$info["count"]; $i++) {
//Handle Image
if(isset($info[$i]["jpegphoto"][0])){
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $info[$i]["jpegphoto"][0]);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
$jpeg = '<img src="data:' . $mime[0] . ';base64,' . base64_encode($info[$i]["jpegphoto"][0]) . '"/>';
}else{
$path = drupal_get_path('module','search_engine');
$jpeg = '<img src="'.$path.'/images/userImage.jpg" />';
}
$rows[$i] = array(
'picture' => $jpeg,
'first' => $info[$i]["givenname"][0],
'last' => $info[$i]["sn"][0],
'role' => $info[$i]["memberof"][0],
'mail' => $info[$i]["mail"][0],
);
}
ldap_close($ds);
return theme('table', array('header'=>$header,'rows'=>$rows));
I'm showing picture, first, last, role, and email in my table. Role contains an array with 3 items, how do I make it go through every item in the array? I know I can't just throw a foreach into the middle of an array.
I need to display all of these.
If you don't need to do anything with the individual roles in that sub-array, e.g. display it only, then simply implode() it into a string:
$rows[$i] = array(
...
'roles' => implode(',', $info[$i]['memberof'])
...
);
If you do need do some with the individual components, then deal with it separately:
$rows[$i] = array(...normal non-array data here);
foreach($info[$i]['memberof'] as $key => $value) {
$rows[$i]['role'][$key] = $value;
}
Are you looking for something like implode()?
$roles = array("role1","role2","role3");
$imploded = implode(",", $roles);
echo $imploded; //should return "role1,role2,role3"

PHP - Random text with two strings

How would I join these two strings and create random link based on the entry list.
// Add a link and the associated image //
$adlink1="http://www.****.com/sale.php";
$adlinkpic1="http://www.***-cdn.com/blogAssets/ad/1.jpg";
$adlink2="http://www.*****.com/sale.php";
$adlinkpic2="http://www.**-cdn.com/blogAssets/ad/2.jpg";
$adlink3="http://www.**.com/product.php?prodref=564_white&ref=AddSphere";
$adlinkpic3="http://www.**-cdn.com/blogAssets/ad/3.jpg";
$adlink4="http://www.**.com/wedding-boutique.php";
$adlinkpic4="http://www.**-cdn.com/blogAssets/ad/4.jpg";
$adlink5="http://www.**.com/made-to-measure-service.php";
$adlinkpic5="http://www.**-cdn.com/blogAssets/ad/5.jpg";
// SHOW ONE AD LINK
srand ((double) microtime() * 1000000);
$adlink[] + $adlinkpic[] = rand(0,count($quotes)-1);
echo "<a href='$adlink'><img src='$adlinkpic' />";
// SHOW TWO AD LINKS /cannot be same
// code here
It is easy to put all of your links in an (associative) array then use array functions to manipulate them:
<?php
$ad = array(
array(
"url" => "http://www.****.com/sale.",
"img" => "http://www.***-cdn.com/blogAssets/ad/1.jpg"
),
array(
"url" => "http://www.*****.com/sale.",
"img" => "http://www.**-cdn.com/blogAssets/ad/2.jpg"
),
array(
"url" => "http://www.**.com/product.php",
"img" => "http://www.**-cdn.com/blogAssets/ad/3.jpg"
),
array(
"url" => "http://www.**.com/wedding-boutique.",
"img" => "http://www.**-cdn.com/blogAssets/ad/4.jpg"
),
array(
"url" => "http://www.**.com/made-to-measure-service.",
"img" => "http://www.**-cdn.com/blogAssets/ad/5.jpg"
)
// more ads
);
$id = array_rand($ad); // choose a random index from the array
echo "<img src=\"{$ad[$id]['img']}\" />\n";
unset($ad[$id]); // remove the chosen one so that it is not displayed on next pass
$id = array_rand($ad);
echo "<img src=\"{$ad[$id]['img']}\" />\n";
unset($ad[$id]);
I'd be tempted to do it something like this:
<?php
// Add a link and the associated image //
$adlink1="http://www.****.com/sale.php";
$adlinkpic1="http://www.***-cdn.com/blogAssets/ad/1.jpg";
$adlink2="http://www.*****.com/sale.php";
$adlinkpic2="http://www.**-cdn.com/blogAssets/ad/2.jpg";
$adlink3="http://www.**.com/product.php?prodref=564_white&ref=AddSphere";
$adlinkpic3="http://www.**-cdn.com/blogAssets/ad/3.jpg";
$adlink4="http://www.**.com/wedding-boutique.php";
$adlinkpic4="http://www.**-cdn.com/blogAssets/ad/4.jpg";
$adlink5="http://www.**.com/made-to-measure-service.php";
$adlinkpic5="http://www.**-cdn.com/blogAssets/ad/5.jpg";
$links = array();
$links[0]=array('link'=>$adlink1,'pic'=>$adlinkpic1);
$links[1]=array('link'=>$adlink2,'pic'=>$adlinkpic2);
$links[2]=array('link'=>$adlink3,'pic'=>$adlinkpic3);
$links[3]=array('link'=>$adlink4,'pic'=>$adlinkpic4);
$links[4]=array('link'=>$adlink5,'pic'=>$adlinkpic5);
$alreadyAdded=array();
for ($i=0;$i<2;$i++) {
$added = false;
while (!$added) {
// generate random number
$rand = mt_rand(0,4);
if (!in_array($rand,$alreadyAdded)) {
echo "<a href='".$links[$rand]['link']."'><img src='".$links[$rand]['pic']."' />";
$added = true;
$alreadyAdded[]=$rand;
}
}
}
Edit: noticed you wanted more than 1 outputted, updated code to reflect.

Categories