entering json data into smart suggest plugin - php

I have purchased the jquery plugin called smart suggest and would like to pass a json array as the data rather than an array.
the current data file 'sample-data.php' looks like:
array('image' => 'assets/images/fruits/apple.jpg', 'description' => 'One of America\'s favorite fruits.'),
'Avocado' => array('image' => 'assets/images/fruits/avocado.jpg', 'description' => 'The avocado is a dense, evergreen tree, shedding many leaves in early spring.'),
'Banana' => array('image' => 'assets/images/fruits/banana.jpg', 'description' => 'Bananas are fast-growing herbaceous perennials arising from underground rhizomes.'),
'Gooseberry' => array('image' => 'assets/images/fruits/gooseberry.jpg', 'description' => 'Gooseberries are deciduous shrubs.'),
'Grape' => array('image' => 'assets/images/fruits/grape.jpg', 'description' => 'Grapes come in large clusters.'),
'Jackfruit' => array('image' => 'assets/images/fruits/jackfruit.jpg', 'description' => 'The jackfruit tree is handsome and stately.'),
'Mango' => array('image' => 'assets/images/fruits/mango.jpg', 'description' => 'Mango trees make handsome landscape specimens and shade trees.'),
'Papaya' => array('image' => 'assets/images/fruits/papaya.jpg', 'description' => 'The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious.'),
'Peach' => array('image' => 'assets/images/fruits/peach.jpg', 'description' => 'These are great in the summertime.'),
'Pear' => array('image' => 'assets/images/fruits/pear.jpg', 'description' => 'Pears are delicious fruits.'),
'Pineapple' => array('image' => 'assets/images/fruits/pineapple.jpg', 'description' => 'The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft.'),
'Rose Apple' => array('image' => 'assets/images/fruits/rose_apple.jpg', 'description' => 'The rose apple is a highly decorative evergreen large shrub.'),
'Tamarind' => array('image' => 'assets/images/fruits/tamarind.jpg', 'description' => 'The bright green, pinnate foliage is dense and feathery in appearance.'),
'White Sapote' => array('image' => 'assets/images/fruits/white_sapote.jpg', 'description' => 'The white sapote forms a medium to very large evergreen tree.'),
);
$vegetables = array(
'Alfalfa' => array('image' => 'assets/images/fruits/alfalfa.jpg', 'description' => 'One cup of raw, sprouted alfalfa seeds, contains 1.32 grams of protein.'),
'Artichoke' => array('image' => 'assets/images/fruits/artichoke.jpg', 'description' => 'One medium artichoke cooked with no added salt has 3.47 grams protein.'),
'Asparagus' => array('image' => 'assets/images/fruits/asparagus.jpg', 'description' => 'Half cup (about 6 spears) cooked with no added salt contains 2.16 grams of protein.'),
'Broccoli' => array('image' => 'assets/images/fruits/broccoli.jpg', 'description' => 'Half cup of broccoli, cooked with no added salt contains 1.86 grams protein.'),
'Carrots' => array('image' => 'assets/images/fruits/carrots.jpg', 'description' => 'Half cup cooked with no added salt contains 0.59 grams protein.'),
'Celery' => array('image' => 'assets/images/fruits/celery.jpg', 'description' => 'One cup of celery, cooked, boiled, drained with no added salt has 1.25 grams protein.'),
'Corn' => array('image' => 'assets/images/fruits/corn.jpg', 'description' => 'One large ear of yellow corn, cooked with no salt contains 4.02 grams protein.'),
'Green Pepper' => array('image' => 'assets/images/fruits/green_pepper.jpg', 'description' => 'One small raw pepper contains 0.64 grams protein.'),
'Mushroom' => array('image' => 'assets/images/fruits/mushroom.jpg', 'description' => 'Half a cup of raw mushrooms contains 1.08 grams of protein.'),
'Onion' => array('image' => 'assets/images/fruits/onion.jpg', 'description' => 'One small onion cooked without salt contains 0.82 grams protein.'),
'Potato' => array('image' => 'assets/images/fruits/potato.jpg', 'description' => 'One medium baked potato without salt contains 4.33 grams of protein.'),
'Spinach' => array('image' => 'assets/images/fruits/spinach.jpg', 'description' => 'One cup of raw spinach contains 0.86 grams of protein.'),
'Squash' => array('image' => 'assets/images/fruits/squash.jpg', 'description' => 'One cup of sliced summer squash, boiled with no added salt contains 1.87 grams of protein.'),
);
?>
this array is passed into the 'search_multiple.php' file which I would like to pass in as JSON:
array(), 'vegetables' => array());
foreach ($fruits as $name => $data)
{
if (stripos($name, $q) !== false)
{
$results['fruits'][$name] = $data;
}
}
foreach ($vegetables as $name => $data)
{
if (stripos($name, $q) !== false)
{
$results['vegetables'][$name] = $data;
}
}
/* Get the data into a format that Smart Suggest will read (see documentation). */
$final_fruits = array('header' => array(), 'data' => array());
$final_fruits['header'] = array(
'title' => 'Fruits', # Appears at the top of this category
'num' => count($results['fruits']), # Displayed as the total number of results.
'limit' => 5 # An arbitrary number that you want to limit the results to.
);
foreach ($results['fruits'] as $name => $data)
{
$final_fruits['data'][] = array(
'primary' => $name, # Title of result row
'secondary' => $data['description'], # Description below title on result row
'image' => $data['image'], # Optional URL of 40x40px image
'onclick' => 'alert(\'You clicked on the '.$name.' fruit!\');', # JavaScript to call when this result is clicked on
'fill_text' => strtolower($name) # Used for "auto-complete fill style" example
);
}
$final_vegetables = array('header' => array(), 'data' => array());
$final_vegetables['header'] = array(
'title' => 'Vegetables', # Appears at the top of this category
'num' => count($results['vegetables']), # Displayed as the total number of results.
'limit' => 5 # An arbitrary number that you want to limit the results to.
);
foreach ($results['vegetables'] as $name => $data)
{
$final_vegetables['data'][] = array(
'primary' => $name, # Title of result row
'secondary' => $data['description'], # Description below title on result row
'image' => $data['image'], # Optional URL of 40x40px image
'onclick' => 'alert(\'You clicked on the '.$name.' vegetable!\');', # JavaScript to call when this result is clicked on
'fill_text' => strtolower($name) # Used for "auto-complete fill style" example
);
}
/* Output JSON */
$final = array($final_fruits, $final_vegetables);
header('Content-type: application/json');
echo json_encode($final);
die();
?>
I would like to know how to pass json data into the 'search_multiple.php' file. For example:
<?php
$fruits = '{
"Apple":{"image":"assets/images/fruits/apple.jpg","description":"One of America\'s favorite fruits."},
"Avocado":{"image":"assets/images/fruits/avocado.jpg","description":"The avocado is a dense, evergreen tree, shedding many leaves in early spring."}
"Banana":{"image":"assets/images/fruits/banana.jpg","description":"Bananas are fast-growing herbaceous perennials arising from underground rhizomes."},
"Gooseberry":{"image":"assets/images/fruits/gooseberry.jpg","description":"Gooseberries are deciduous shrubs."}
"Grape":{"image":"assets/images/fruits/grape.jpg","description":"Grapes come in large clusters."},
"Jackfruit":{"image":"assets/images/fruits/jackfruit.jpg","description":"The jackfruit tree is handsome and stately."}
"Mango":{"image":"assets/images/fruits/mango.jpg","description":"Mango trees make handsome landscape specimens and shade trees."},
"Papaya":{"image":"assets/images/fruits/papaya.jpg","description":"The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious."}
"Peach":{"image":"assets/images/fruits/peach.jpg","description":"These are great in the summertime."},
"Pear":{"image":"assets/images/fruits/pear.jpg","description":"Pears are delicious fruits."},
"Pineapple":{"image":"assets/images/fruits/pineapple.jpg","description":"The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft."}
"Rose Apple":{"image":"assets/images/fruits/rose_apple.jpg","description":"The rose apple is a highly decorative evergreen large shrub."},
"Tamarind":{"image":"assets/images/fruits/tamarind.jpg","description":"The bright green, pinnate foliage is dense and feathery in appearance."}
"White Sapote":{"image":"assets/images/fruits/white_sapote.jpg","description":"One cup of sliced summer squash, boiled with no added salt contains 1.87 grams of protein."},
}';
$vegetables = '{
"Alfalfa":{"image":"assets/images/fruits/apple.jpg","description":"One of America\'s favorite fruits."},
"Artichoke":{"image":"assets/images/fruits/avocado.jpg","description":"The avocado is a dense, evergreen tree, shedding many leaves in early spring."}
"Asparagus":{"image":"assets/images/fruits/banana.jpg","description":"Bananas are fast-growing herbaceous perennials arising from underground rhizomes."},
"Broccoli":{"image":"assets/images/fruits/gooseberry.jpg","description":"Gooseberries are deciduous shrubs."}
"Carrots":{"image":"assets/images/fruits/grape.jpg","description":"Grapes come in large clusters."},
"Celery":{"image":"assets/images/fruits/jackfruit.jpg","description":"The jackfruit tree is handsome and stately."}
"Corn":{"image":"assets/images/fruits/mango.jpg","description":"Mango trees make handsome landscape specimens and shade trees."},
"Green Pepper":{"image":"assets/images/fruits/papaya.jpg","description":"The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious."}
"Mushroom":{"image":"assets/images/fruits/peach.jpg","description":"These are great in the summertime."},
"Onion":{"image":"assets/images/fruits/pear.jpg","description":"Pears are delicious fruits."},
"Potato":{"image":"assets/images/fruits/pineapple.jpg","description":"The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft."}
"Spinach":{"image":"assets/images/fruits/rose_apple.jpg","description":"The rose apple is a highly decorative evergreen large shrub."},
"Squash":{"image":"assets/images/fruits/tamarind.jpg","description":"The bright green, pinnate foliage is dense and feathery in appearance."}
}';
?>
The documentation is on http://jamesskidmore.com/scripts/smartsuggest/
I have hosted my current progress on http://kabeerpc.tk.

There is no such thing as a JSON array; an array in a JSON document is merely a representation (or serialization) of an array. Therefore, you can simply decode the JSON:
<?php
$fruits_json = '{
"Apple":{"image":"assets/images/fruits/apple.jpg",
"description":"One of America\'s favorite fruits."},
"Avocado":{"image":"assets/images/fruits/avocado.jpg",
"description":"The avocado is a dense, evergreen tree."}}';
$vegetables_json = '{
"Alfalfa":{"image":"assets/images/fruits/pear.jpg",
"description":"An american alfafa."},
"Artichoke":{"image":"assets/images/fruits/peach.jpg",
"description":"An American artichoke."}}';
// Decode input JSON
$fruits = json_decode($fruits_json, true);
$vegetables = json_decode($vegetables_json, true);
$q = isset($_GET['q']) ? $_GET['q'] : '';
$final = array(
_construct_smartSuggestion('fruits', $fruits, $q),
_construct_smartSuggestion('vegetables', $vegetables, $q)
);
header('Content-type: application/json');
die(json_encode($final));
function _construct_smartSuggestion($name, $described, $q) {
$data = array();
foreach ($described as $dname=>$d) {
// Search for the search query
if (stripos($dname, $q) === false &&
stripos($d['description'], $q) === false) {
continue;
}
$data[] = array('primary' => $dname,
'secondary' => $d['description'],
'image' => $d['image']);
}
$header = array('title'=>$name, 'num'=>count($data), 'limit'=>5);
return array('header'=>$header, 'data'=>$data);
}
Make sure that your JSON serialization is valid. Your example JSON is missing commas after many entries (for example Avocado).
Here's a live demo. Searching for American will produce three of the four available results there.

Related

Key sort an array of ad size dimensions? 300x250 should come before 300x1050

I'm working with Google AdSense sizes. I have the array below, but I also allow users to enter their own custom ad sizes. I want their ad size to be placed in the correct order in the array. The problem is when the second number in the ad size is over 999, it gets out of order.
$adsizes = array(
# Google Adsense Display and Text Unit Sizes
'970x90' => 'Large Leaderboard',
'728x90' => 'Leaderboard',
'468x60' => 'Banner ',
'336x280' => 'Large Rectangle',
'320x100' => 'Large Mobile Banner',
'320x50' => 'Mobile Banner',
'300x600' => 'Large Skyscraper',
'300x250' => 'Medium Rectangle',
'250x250' => 'Square ',
'234x60' => 'Half Banner',
'200x200' => 'Small Square',
'200x200' => 'Small Square',
'180x150' => 'Small Rectangle',
'160x600' => 'Wide Skyscraper',
'125x125' => 'Button',
'120x600' => 'Skyscraper',
'120x240' => 'Vertical Banner',
# Google Adsense Link Unit Sizes
'728x15' => 'Displays 4 links',
'468x15' => 'Displays 4 links',
'200x90' => 'Displays 3 links',
'180x90' => 'Displays 3 links',
'160x90' => 'Displays 3 links',
'120x90' => 'Displays 3 links',
);
For example, if the user enters 300x1050 as their ad size, it would show up below the 300x250 ad here if I just sorted with ksort(). How can I have the size 300x1050 inserted into the correct position which is just above 300x600 in this instance?
I'm assuming you want to sort by vertex length:
200x99999
300x900
300x1000
400x400
In this case you can get away with using strnatcmp (and uksort) to do a natural order sort (22 before 150, 3 before 190).
uksort($adsizes, 'strnatcmp');
If you want to sort by surface area:
300x900
400x400
300x1000
200x99999
you will need to write your own sort function

Bibtex php preg_match_all

I have a text file with a Bibtex export.
The text file has a number of entries following the pattern below.
#article{ls_leimeister,
added-at = {2013-01-18T11:14:11.000+0100},
author = {Wegener, R. and Leimeister, J. M.},
biburl = {http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister},
journal = {International Journal of Technology Enhanced Learning (to appear)},
keywords = {Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe},
note = {JML_390},
title = {Virtual Learning Communities: Success Factors and Challenges},
year = 2013
}
I want to use php and considered preg_match_all
The following didnt get me anywhere:
preg_match_all('/#^.*}$/', file_get_contents($file_path),$results);
I wanted to start simple, but that didnt really work.
I am kinda new to php RegEx.
The perfect final output would be:
Array
(
[0] => Array
(
['type'] => article
['unique_name'] => ls_leimeister
['added-at'] => 2013-01-18T11:14:11.000+0100
['author'] => Wegener, R. and Leimeister, J. M.
['biburl'] => http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister
['journal'] => International Journal of Technology Enhanced Learning (to appear)
['keywords'] => Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe
['note'] => JML_390
['title'] => Virtual Learning Communities: Success Factors and Challenges
['year'] => 2013
)
[1] => Array
(
[...] => …
)
)
Try this : Here I have fetched only type and unique_name, by looking at it, you can fetch all others.
$str = '#article{ls_leimeister,
added-at = {2013-01-18T11:14:11.000+0100},
author = {Wegener, R. and Leimeister, J. M.},
biburl = {http://www.bibsonomy.org/bibtex/27bb26b4b4858439f81aa0ec777944ac5/ls_leimeister},
journal = {International Journal of Technology Enhanced Learning (to appear)},
keywords = {Challenges Communities: Factors Learning Success VirtualCommunity and itegpub pub_jml pub_rwe},
note = {JML_390},
title = {Virtual Learning Communities: Success Factors and Challenges},
year = 2013
}';
preg_match_all('/#(?P<type>\w+){(?P<unique_name>\w+),(.*)/',$str,$matches);
echo $matches['type'][0];
echo "<br>";
echo $matches['unique_name'][0];
echo "<br>";
echo "<pre>";
print_r($matches);
Output array format will be little different from yours, but you can change this format to yours.
Pattern: /^#([^{]+)\{([^,]+),\s*$|^\s*([^\R#=]+) = \{(.*?)}/ms (Demo)
This pattern has two alternatives; each containing two capture groups.
type and unique_name are captured and stored in elements [1] and [2].
all other key-value pairs are stored in elements [3] and [4].
This separated array storage allows reliable processing when constructing the desired output array structure.
Input:
$bibtex='#BOOK{ko,
title = {Wissenschaftlich schreiben leicht gemacht},
publisher = {Haupt},
year = {2011},
author = {Kornmeier, M.},
number = {3154},
series = {UTB},
address = {Bern},
edition = {4},
subtitle = {für Bachelor, Master und Dissertation}
}
#BOOK{nial,
title = {Wissenschaftliche Arbeiten schreiben mit Word 2010},
publisher = {Addison Wesley},
year = {2011},
author = {Nicol, N. and Albrecht, R.},
address = {München},
edition = {7}
}
#ARTICLE{shome,
author = {Scholz, S. and Menzl, S.},
title = {Alle Wege führen nach Rom},
journal = {Medizin Produkte Journal},
year = {2011},
volume = {18},
pages = {243-254},
subtitle = {ein Vergleich der regulatorischen Anforderungen und Medizinprodukte
in Europa und den USA},
issue = {4}
}
#INBOOK{shu,
author = {Schulz, C.},
title = {Corporate Finance für den Mittelstand},
booktitle = {Praxishandbuch Firmenkundengeschäft},
year = {2010},
editor = {Hilse, J. and Netzel, W and Simmert, D.B.},
booksubtitle = {Geschäftsfelder Risikomanagement Marketing},
publisher = {Gabler},
pages = {97-107},
location = {Wiesbaden}
}';
Method: (Demo)
$pattern='/^#([^{]+)\{([^,]+),\s*$|^\s*([^\R#=]+) = \{(.*?)}/ms';
if(preg_match_all($pattern,$bibtex,$out,PREG_SET_ORDER)){
foreach($out as $line){
if(isset($line[1])){
if(!isset($line[3])){ // this is the starting line of a new set
if(isset($temp)){
$result[]=$temp; // send $temp data to permanent storage
}
$temp=['type'=>$line[1],'unique_name'=>$line[2]]; // declare fresh new $temp
}else{
$temp[$line[3]]=$line[4]; // continue to store the $temp data
}
}
}
$result[]=$temp; // store the final $temp data
}
var_export($result);
Output:
array (
0 =>
array (
'type' => 'BOOK',
'unique_name' => 'ko',
'title' => 'Wissenschaftlich schreiben leicht gemacht',
'publisher' => 'Haupt',
'year' => '2011',
'author' => 'Kornmeier, M.',
'number' => '3154',
'series' => 'UTB',
'address' => 'Bern',
'edition' => '4',
'subtitle' => 'für Bachelor, Master und Dissertation',
),
1 =>
array (
'type' => 'BOOK',
'unique_name' => 'nial',
'title' => 'Wissenschaftliche Arbeiten schreiben mit Word 2010',
'publisher' => 'Addison Wesley',
'year' => '2011',
'author' => 'Nicol, N. and Albrecht, R.',
'address' => 'München',
'edition' => '7',
),
2 =>
array (
'type' => 'ARTICLE',
'unique_name' => 'shome',
'author' => 'Scholz, S. and Menzl, S.',
'title' => 'Alle Wege führen nach Rom',
'journal' => 'Medizin Produkte Journal',
'year' => '2011',
'volume' => '18',
'pages' => '243-254',
'subtitle' => 'ein Vergleich der regulatorischen Anforderungen und Medizinprodukte
in Europa und den USA',
'issue' => '4',
),
3 =>
array (
'type' => 'INBOOK',
'unique_name' => 'shu',
'author' => 'Schulz, C.',
'title' => 'Corporate Finance für den Mittelstand',
'booktitle' => 'Praxishandbuch Firmenkundengeschäft',
'year' => '2010',
'editor' => 'Hilse, J. and Netzel, W and Simmert, D.B.',
'booksubtitle' => 'Geschäftsfelder Risikomanagement Marketing',
'publisher' => 'Gabler',
'pages' => '97-107',
'location' => 'Wiesbaden',
),
)
Here is the site that I extracted new sample input strings from.

Applying a custom order to a multi-dimensional array

I have this array
$arr = array(
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
),
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
)
);
which i need to look like this
$arr = array(
'two' => array(
'slidertitle' => 'second slider',
'sliderlocation' => 'http://localhost/images/2.jpg',
'sliderdescription' => 'this space was reserved for a link source code here',
'sliderposition' => 2
),
'six' => array(
'slidertitle' => 'sixth slider',
'sliderlocation' => 'http://localhost/images/6.jpg',
'sliderdescription' => 'this is the sixth slider,like,really!',
'sliderposition' => 6
),
'one' => array(
'slidertitle' => 'lorem ipsum',
'sliderlocation' => 'http://localhost/images/1.jpg',
'sliderdescription' => 'this is a good lorem ipsum image',
'sliderposition' => 1
)
);
I am attempting to do that by defining the expected array structure and introducing a dummy array.I then chunk the array and merge each chunk to the array format and i plan to finally unset the dummy and i am left with the array i want and in the order i want.
$arrayFormat = array(
'dummy' => array(
'slidertitle' => 'xxxx',
'sliderlocation' => 'xxxxxxx',
'sliderdescription' => 'xxxxxx',
'sliderposition' => 0
)
);
$arrayLength = count($arr);
$afterChunk = array_chunk($arr,$arrayLength);
$one = $afterChunk[0][0];
$two = $afterChunk[0][1];
$mergedArray = array_merge($arrayFormat,$one);
$secondMergedArray = array_merge($mergedArray,$two);
echo '<pre>';
print_r($secondMergedArray);
echo '</pre>';
The problem is array_chunk() does not include the key of the array so i am getting
Array (
[dummy] => Array
(
[slidertitle] => xxxx
[sliderlocation] => xxxxxxx
[sliderdescription] => xxxxxx
[sliderposition] => 0
)
[slidertitle] => second slider
[sliderlocation] => http://localhost/images/2.jpg
[sliderdescription] => this space was reserved for a link source code here
[sliderposition] => 2 )
when i print_r($secondMergedArray);.is there something that can be done to array_chunk() to include the array key or is there any other array function that can help me get individual array inclusive of the key?.
It's really hard to tell what you're wanting in terms of how to sort the elements. You've not been very clear in the question. There has to be something in the array that you know what order it needs to be.
In the absence of any clues as to what that is, I'm going to assume you want to specify the order of the array keys manually.
So, the current array is array('one'=>... , 'two'=>... , 'six'=>... ) and you want to sort those keys in an order you want to specify manually.
The solution is to use the uksort() function, along with a separate array specifying your sort order:
$arr = ... //input array as specified in the question
$sortOrder = array('two','one','six');
uksort($arr, function ($a, $b) use ($sortOrder) {
$sortMe = array_flip($sortOrder);
if ($sortMe[$a] == $sortMe[$b]) { return 0; }
return ($sortMe[$a] < $sortMe[$b]) ? -1 : 1;
});
print_r($arr);
Outputs your array in 'two','one','six' order. Change the $sortOrder array as required.
Hope that helps.
Note: the syntax I've provided above only works in PHP 5.3 and above. (if you're using an older version, you need to upgrade)
use uksort() for custom order for multidimensional array
http://php.net/manual/en/function.uksort.php

passing json data into smart suggest jquery plugin

I have purchased the jquery plugin called smart suggest and would like to pass a json array as the data rather than an array.
the current data file 'sample-data.php' looks like:
array('image' => 'assets/images/fruits/apple.jpg', 'description' => 'One of America\'s favorite fruits.'),
'Avocado' => array('image' => 'assets/images/fruits/avocado.jpg', 'description' => 'The avocado is a dense, evergreen tree, shedding many leaves in early spring.'),
'Banana' => array('image' => 'assets/images/fruits/banana.jpg', 'description' => 'Bananas are fast-growing herbaceous perennials arising from underground rhizomes.'),
'Gooseberry' => array('image' => 'assets/images/fruits/gooseberry.jpg', 'description' => 'Gooseberries are deciduous shrubs.'),
'Grape' => array('image' => 'assets/images/fruits/grape.jpg', 'description' => 'Grapes come in large clusters.'),
'Jackfruit' => array('image' => 'assets/images/fruits/jackfruit.jpg', 'description' => 'The jackfruit tree is handsome and stately.'),
'Mango' => array('image' => 'assets/images/fruits/mango.jpg', 'description' => 'Mango trees make handsome landscape specimens and shade trees.'),
'Papaya' => array('image' => 'assets/images/fruits/papaya.jpg', 'description' => 'The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious.'),
'Peach' => array('image' => 'assets/images/fruits/peach.jpg', 'description' => 'These are great in the summertime.'),
'Pear' => array('image' => 'assets/images/fruits/pear.jpg', 'description' => 'Pears are delicious fruits.'),
'Pineapple' => array('image' => 'assets/images/fruits/pineapple.jpg', 'description' => 'The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft.'),
'Rose Apple' => array('image' => 'assets/images/fruits/rose_apple.jpg', 'description' => 'The rose apple is a highly decorative evergreen large shrub.'),
'Tamarind' => array('image' => 'assets/images/fruits/tamarind.jpg', 'description' => 'The bright green, pinnate foliage is dense and feathery in appearance.'),
'White Sapote' => array('image' => 'assets/images/fruits/white_sapote.jpg', 'description' => 'The white sapote forms a medium to very large evergreen tree.'),
);
$vegetables = array(
'Alfalfa' => array('image' => 'assets/images/fruits/alfalfa.jpg', 'description' => 'One cup of raw, sprouted alfalfa seeds, contains 1.32 grams of protein.'),
'Artichoke' => array('image' => 'assets/images/fruits/artichoke.jpg', 'description' => 'One medium artichoke cooked with no added salt has 3.47 grams protein.'),
'Asparagus' => array('image' => 'assets/images/fruits/asparagus.jpg', 'description' => 'Half cup (about 6 spears) cooked with no added salt contains 2.16 grams of protein.'),
'Broccoli' => array('image' => 'assets/images/fruits/broccoli.jpg', 'description' => 'Half cup of broccoli, cooked with no added salt contains 1.86 grams protein.'),
'Carrots' => array('image' => 'assets/images/fruits/carrots.jpg', 'description' => 'Half cup cooked with no added salt contains 0.59 grams protein.'),
'Celery' => array('image' => 'assets/images/fruits/celery.jpg', 'description' => 'One cup of celery, cooked, boiled, drained with no added salt has 1.25 grams protein.'),
'Corn' => array('image' => 'assets/images/fruits/corn.jpg', 'description' => 'One large ear of yellow corn, cooked with no salt contains 4.02 grams protein.'),
'Green Pepper' => array('image' => 'assets/images/fruits/green_pepper.jpg', 'description' => 'One small raw pepper contains 0.64 grams protein.'),
'Mushroom' => array('image' => 'assets/images/fruits/mushroom.jpg', 'description' => 'Half a cup of raw mushrooms contains 1.08 grams of protein.'),
'Onion' => array('image' => 'assets/images/fruits/onion.jpg', 'description' => 'One small onion cooked without salt contains 0.82 grams protein.'),
'Potato' => array('image' => 'assets/images/fruits/potato.jpg', 'description' => 'One medium baked potato without salt contains 4.33 grams of protein.'),
'Spinach' => array('image' => 'assets/images/fruits/spinach.jpg', 'description' => 'One cup of raw spinach contains 0.86 grams of protein.'),
'Squash' => array('image' => 'assets/images/fruits/squash.jpg', 'description' => 'One cup of sliced summer squash, boiled with no added salt contains 1.87 grams of protein.'),
);
?>
this array is passed into the 'search_multiple.php' file which I would like to pass in as JSON:
array(), 'vegetables' => array());
foreach ($fruits as $name => $data)
{
if (stripos($name, $q) !== false)
{
$results['fruits'][$name] = $data;
}
}
foreach ($vegetables as $name => $data)
{
if (stripos($name, $q) !== false)
{
$results['vegetables'][$name] = $data;
}
}
/* Get the data into a format that Smart Suggest will read (see documentation). */
$final_fruits = array('header' => array(), 'data' => array());
$final_fruits['header'] = array(
'title' => 'Fruits', # Appears at the top of this category
'num' => count($results['fruits']), # Displayed as the total number of results.
'limit' => 5 # An arbitrary number that you want to limit the results to.
);
foreach ($results['fruits'] as $name => $data)
{
$final_fruits['data'][] = array(
'primary' => $name, # Title of result row
'secondary' => $data['description'], # Description below title on result row
'image' => $data['image'], # Optional URL of 40x40px image
'onclick' => 'alert(\'You clicked on the '.$name.' fruit!\');', # JavaScript to call when this result is clicked on
'fill_text' => strtolower($name) # Used for "auto-complete fill style" example
);
}
$final_vegetables = array('header' => array(), 'data' => array());
$final_vegetables['header'] = array(
'title' => 'Vegetables', # Appears at the top of this category
'num' => count($results['vegetables']), # Displayed as the total number of results.
'limit' => 5 # An arbitrary number that you want to limit the results to.
);
foreach ($results['vegetables'] as $name => $data)
{
$final_vegetables['data'][] = array(
'primary' => $name, # Title of result row
'secondary' => $data['description'], # Description below title on result row
'image' => $data['image'], # Optional URL of 40x40px image
'onclick' => 'alert(\'You clicked on the '.$name.' vegetable!\');', # JavaScript to call when this result is clicked on
'fill_text' => strtolower($name) # Used for "auto-complete fill style" example
);
}
/* Output JSON */
$final = array($final_fruits, $final_vegetables);
header('Content-type: application/json');
echo json_encode($final);
die();
?>
I would like to know how to pass json data into the 'search_multiple.php' file. For example:
<?php
$fruits = '{
"Apple":{"image":"assets/images/fruits/apple.jpg","description":"One of America\'s favorite fruits."},
"Avocado":{"image":"assets/images/fruits/avocado.jpg","description":"The avocado is a dense, evergreen tree, shedding many leaves in early spring."}
"Banana":{"image":"assets/images/fruits/banana.jpg","description":"Bananas are fast-growing herbaceous perennials arising from underground rhizomes."},
"Gooseberry":{"image":"assets/images/fruits/gooseberry.jpg","description":"Gooseberries are deciduous shrubs."}
"Grape":{"image":"assets/images/fruits/grape.jpg","description":"Grapes come in large clusters."},
"Jackfruit":{"image":"assets/images/fruits/jackfruit.jpg","description":"The jackfruit tree is handsome and stately."}
"Mango":{"image":"assets/images/fruits/mango.jpg","description":"Mango trees make handsome landscape specimens and shade trees."},
"Papaya":{"image":"assets/images/fruits/papaya.jpg","description":"The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious."}
"Peach":{"image":"assets/images/fruits/peach.jpg","description":"These are great in the summertime."},
"Pear":{"image":"assets/images/fruits/pear.jpg","description":"Pears are delicious fruits."},
"Pineapple":{"image":"assets/images/fruits/pineapple.jpg","description":"The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft."}
"Rose Apple":{"image":"assets/images/fruits/rose_apple.jpg","description":"The rose apple is a highly decorative evergreen large shrub."},
"Tamarind":{"image":"assets/images/fruits/tamarind.jpg","description":"The bright green, pinnate foliage is dense and feathery in appearance."}
"White Sapote":{"image":"assets/images/fruits/white_sapote.jpg","description":"One cup of sliced summer squash, boiled with no added salt contains 1.87 grams of protein."},
}';
$vegetables = '{
"Alfalfa":{"image":"assets/images/fruits/apple.jpg","description":"One of America\'s favorite fruits."},
"Artichoke":{"image":"assets/images/fruits/avocado.jpg","description":"The avocado is a dense, evergreen tree, shedding many leaves in early spring."}
"Asparagus":{"image":"assets/images/fruits/banana.jpg","description":"Bananas are fast-growing herbaceous perennials arising from underground rhizomes."},
"Broccoli":{"image":"assets/images/fruits/gooseberry.jpg","description":"Gooseberries are deciduous shrubs."}
"Carrots":{"image":"assets/images/fruits/grape.jpg","description":"Grapes come in large clusters."},
"Celery":{"image":"assets/images/fruits/jackfruit.jpg","description":"The jackfruit tree is handsome and stately."}
"Corn":{"image":"assets/images/fruits/mango.jpg","description":"Mango trees make handsome landscape specimens and shade trees."},
"Green Pepper":{"image":"assets/images/fruits/papaya.jpg","description":"The papaya is a short-lived, fast-growing, woody, large herb to 10 or 12 feet in height. It is also regarded by some as being delicious."}
"Mushroom":{"image":"assets/images/fruits/peach.jpg","description":"These are great in the summertime."},
"Onion":{"image":"assets/images/fruits/pear.jpg","description":"Pears are delicious fruits."},
"Potato":{"image":"assets/images/fruits/pineapple.jpg","description":"The pineapple plant is a herbaceous perennial, 2-1/2 to 5 ft."}
"Spinach":{"image":"assets/images/fruits/rose_apple.jpg","description":"The rose apple is a highly decorative evergreen large shrub."},
"Squash":{"image":"assets/images/fruits/tamarind.jpg","description":"The bright green, pinnate foliage is dense and feathery in appearance."}
}';
?>
Please help me!! I cannot code in PHP
Thanks
Kabeer
$dp=mysql_select_db('test');
mysql_query('SET NAMES UTF8');
$sql = mysql_query('select * from users');
while($res = mysql_fetch_assoc($sql)){
$users[$res['username']] = array();
$users[$res['username']]['image'] = $res['profile_picture'];
$users[$res['username']]['email'] = $res['email'];
}
I've a database called test and table called users with fields(username, email, profile_picture), I'm searching for usernames to have the email and the image(look like facebook search).
This array will generate you the array you want from the database automatically, just search for user name, change in it to match your needs.

how to replace text in a mysql database content array

im trying to get rid of unneccesary text in my database content.My code looks like this:
if(mysql_num_rows($result))
$items[] = array();
while($row = mysql_fetch_assoc($result)) {
$items[] = array('id' => $row['id'], 'cat' => $row['cat'], 'type' => $row['type'], 'name' => $row['name'], 'sub_title' => $row['sub_title'], 'display_date' => $row['display_date'], 'slug' => $row['slug'], 'ticket_url' => $row['ticket_url'], 'status' => $row['status'], 'content' => $row['content'], 'display_until' => $row['display_until'], 'photo' => $row['photo'], 'thumb' => $row['thumb']);
$removals = array('\n','\r','\t','<\/div>\r\n');
$spaces = "";
$parsedText = str_replace($removals, $spaces, $items);
}
echo json_encode(array('events'=>$items));
And the content then displays like this:
{"events":[[],{"id":"66","cat":"9","type":"2","name":"Oileán - A Celebration of the Blasket Islands","sub_title":"National Folk Theatre","display_date":"Tues 4th - Thurs 6th May at 8.30pm","slug":"This production celebrates life on the Blasket Islands in times past, exploring the way of life of the islanders and their spirit of survival. Oileán captures the essence of this island community, their traditions and customs, their wealth of song and story, their love of life and their strong kinship with one another. ","ticket_url":"","status":"1","content":"
\r\n\tPresented by the members of the National Folk Theatre of Ireland</strong>, this production celebrates and explores Blasket Island living while also challenging our own notions of identity as contemporary islanders. </div>\r\n
\r\n\t </div>\r\n
\r\n\tPremiered in 2003, Oileán</strong></em> marked the 50th</sup> anniversary of the departure of the Blasket Islanders to the mainland. The Great Blasket Island, located off the coast of West Kerry still retains an almost mystical significance for many, both from Ireland and abroad. The way of life of the islanders and their spirit of survival is framed in this production, which captures the essence of this island community, their traditions and customs, their wealth of song and story, their love of life and their strong kinship with one another. </div>\r\n
\r\n\t </div>\r\n
\r\n\tOileán</i></b> is delivered in the unique Siamsa style through the medium of dance, mime, music and song.</div>\r\n
\r\n\t </div>\r\n
\r\n\t
\r\n\t\t </div>\r\n\t
\r\n\t\tPlease note that due to the popularity of performances by the National Folk Theatre</strong>, some productions may be sold out well in advance and tickets may not be available on-line. However, we often have returns and tickets may be available nearer to the day of a performance</strong>. Please contact us directly by phone on: +353 (0)66 7123055.</em></div>\r\n\t
\r\n\t\t </div>\r\n\t
\r\n\t\t </div>\r\n</div>\r\n","display_until":"20100504","photo":"1269869378-oilean_side.jpg","thumb":"1269869378-oilean_thumb.jpg"},
The above display is the first item in the DB.
Im trying the replace all the \r , \n , etc in the above content?How can i go about this?Is what i have allready on the right track?
2 things
if(mysql_num_rows($result))
$items = array(); // not $items[], that would set the first item as an array
while($row = mysql_fetch_assoc($result)) {
$removals = array("\n","\r","\t","<\/div>\r\n");
$spaces = "";
$items[] = array(
'id' => $row['id'],
'cat' => $row['cat'],
'type' => $row['type'],
'name' => $row['name'],
'sub_title' => $row['sub_title'],
'display_date' => $row['display_date'],
'slug' => $row['slug'],
'ticket_url' => $row['ticket_url'],
'status' => $row['status'],
// replace the content here
// youll want to use preg_replace though otherwise youll end up with multiple </div>'s
'content' => str_replace( $removals, $spaces, $row['content'] ),
'display_until' => $row['display_until'],
'photo' => $row['photo'],
'thumb' => $row['thumb']
);
}
echo json_encode(array('events'=>$items));

Categories