Data Matrix Barcode split to different data - php

I have a data matrix barcode that have the input
Data Matrix Barcode = 0109556135082301172207211060221967 21Sk4YGvF811210721
I wish to have output as below:-
Items
Output
Gtin
09556135082301
Expire Date
21-07-22
Batch No
60221967
Serial No
Sk4YGvF8
Prod Date
21-07-21
But My coding didn't detect after the space
$str = "0109556135082301172207211060221967 21Sk4YGvF811";
if ($str != null){
$ais = explode("_",$str);
for ($aa=0;$aa<sizeof($ais);$aa++)
{
$ary = $ais[$aa];
while(strlen($ary) > 0) {
if (substr($ary,0,2)=="01"){
$gtin = substr($ary,2,14);
$ary = substr($ary,-(strlen($ary)-16));
}
else if (substr($ary,0,2)=="17"){
$expirydate = substr($ary,6,2)."-".substr($ary,4,2)."-20".substr($ary,2,2);
$ary = substr($ary,-(strlen($ary)-8));
}
else if (substr($ary,0,2)=="10"){
$batchno = substr($ary,2,strlen($ary)-2);
$ary = "";
}
else if (substr($ary,0,2)=="21"){
$serialno = substr($ary,2,strlen($ary)-2);
$ary = "";
}
else if (substr($ary,0,2)=="11"){
$proddate = substr($ary,6,2)."-".substr($ary,4,2)."-20".substr($ary,2,2);
$ary = substr($ary,-(strlen($ary)-8));
}
else {
$oth = "";
}
}
}
My code output https://onecompiler.com/php/3yg6gs5ea didn't come out the result I expected. Anyway to modify it?

Solution
You can use a regex to make it short and easy.
Note
Your string does not contain all the characters of the code given in the description.
Code
$str = "0109556135082301172207211060221967 21Sk4YGvF811210721";
$datePattern = '/(\d\d)(\d\d)(\d\d)/';
$dateReplacement = '\3-\2-\1';
$matches = [];
preg_match('/(?<gtin>.{18})(?<expire>.{6})(?<batch>.*?)\s(?<serial>.{12}(?<prod>.{6}))/', $str, $matches);
$matches['expire'] = preg_replace($datePattern, $dateReplacement, $matches['expire']);
$matches['prod'] = preg_replace($datePattern, $dateReplacement, $matches['prod']);
$matches = array_filter($matches, fn($value, $key) => !is_numeric($key), ARRAY_FILTER_USE_BOTH);
$keyMap = [
'gtin' => 'Gtin',
'expire' => 'Expire Date',
'batch' => 'Batch No.',
'serial' => 'Serial No.',
'prod' => 'Production Date',
];
foreach ($keyMap as $key => $output) {
echo "<tr><td>$output</td><td>{$matches[$key]}</td></tr>\n";
}
Output
<tr><td>Gtin</td><td>010955613508230117</td></tr>
<tr><td>Expire Date</td><td>21-07-22</td></tr>
<tr><td>Batch No.</td><td>1060221967</td></tr>
<tr><td>Serial No.</td><td>21Sk4YGvF811210721</td></tr>
<tr><td>Production Date</td><td>21-07-21</td></tr>

Related

Creating a dynamic hierarchical array in PHP

I have this general data structure:
$levels = array('country', 'state', 'city', 'location');
I have data that looks like this:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', ... )
);
I want to create hierarchical arrays such as
$hierarchy = array(
'USA' => array(
'New York' => array(
'NYC' => array(
'Central Park' => 123,
),
),
),
'Germany' => array(...),
);
Generally I would just create it like this:
$final = array();
foreach ($locations as $L) {
$final[$L['country']][$L['state']][$L['city']][$L['location']] = $L['count'];
}
However, it turns out that the initial array $levels is dynamic and can change in values and length So I cannot hard-code the levels into that last line, and I do not know how many elements there are. So the $levels array might look like this:
$levels = array('country', 'state');
Or
$levels = array('country', 'state', 'location');
The values will always exist in the data to be processed, but there might be more elements in the processed data than in the levels array. I want the final array to only contain the values that are in the $levels array, no matter what additional values are in the original data.
How can I use the array $levels as a guidance to dynamically create the $final array?
I thought I could just build the string $final[$L['country']][$L['state']][$L['city']][$L['location']] with implode() and then run eval() on it, but is there are a better way?
Here's my implementation. You can try it out here:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', 'state'=>'Blah', 'city'=>'NY', 'location'=>'Testing', 'count'=>54),
);
$hierarchy = array();
$levels = array_reverse(
array('country', 'state', 'city', 'location')
);
$lastLevel = 'count';
foreach ( $locations as $L )
{
$array = $L[$lastLevel];
foreach ( $levels as $level )
{
$array = array($L[$level] => $array);
}
$hierarchy = array_merge_recursive($hierarchy, $array);
}
print_r($hierarchy);
Cool question. A simple approach:
$output = []; //will hold what you want
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++) $str_to_eval .= "[\$loc[\$levels[$i]]]";
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval); //will build the array for this location
}
Live demo
If your dataset always in fixed structure, you might just loop it
$data[] = [country=>usa, state=>ny, city=>...]
to
foreach ($data as $row) {
$result[][$row[country]][$row[state]][$row[city]] = ...
}
In case your data is dynamic and the levels of nested array is also dynamic, then the following is an idea:
/* convert from [a, b, c, d, ...] to [a][b][...] = ... */
function nested_array($rows, $level = 1) {
$data = array();
$keys = array_slice(array_keys($rows[0]), 0, $level);
foreach ($rows as $r) {
$ref = &$data[$r[$keys[0]]];
foreach ($keys as $j => $k) {
if ($j) {
$ref = &$ref[$r[$k]];
}
unset($r[$k]);
}
$ref = count($r) > 1 ? $r : reset($r);
}
return $data;
}
try this:
<?php
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harbor', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$nk = array();
foreach($locations as $l) {
$jsonstr = json_encode($l);
preg_match_all('/"[a-z]+?":/',$jsonstr,$e);
$narr = array();
foreach($e[0] as $k => $v) {
if($k == 0 ) {
$narr[] = '';
} else {
$narr[] = ":{";
}
}
$narr[count($e[0]) -1] = ":" ;
$narr[] = "";
$e[0][] = ",";
$jsonstr = str_replace($e[0],$narr,$jsonstr).str_repeat("}",count($narr)-3);
$nk [] = $ko =json_decode($jsonstr,TRUE);
}
print_r($nk);
Database have three field:
here Name conatin contry state and city name
id,name,parentid
Pass the contry result to array to below function:
$data['contry']=$this->db->get('contry')->result_array();
$return['result']=$this->ordered_menu( $data['contry'],0);
echo "<pre>";
print_r ($return['result']);
echo "</pre>";
Create Function as below:
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}

Need help php to json array

I am having a string below
$string = ot>4>om>6>we>34>ff>45
I would like the JSON output be like
[{"name":"website","data":["ot","om","we","ff"]}]
and
[{"name":"websitedata","data":["4","6","34","45"]}]
what I've tried
$query = mysql_query("SELECT month, wordpress, codeigniter, highcharts FROM project_requests");
$category = array();
$category['name'] = 'website';
$series1 = array();
$series1['name'] = 'websitedata';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['month'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
print json_encode($result, JSON_NUMERIC_CHECK);
but the above code is applicable only if the data are present in rows from a mysql table, what i want is achieve the same result with the data from the above string. that is
$string = ot>4>om>6>we>34>ff>45
NEW UPDATE:
I would like to modify the same string
$string = ot>4>om>6>we>34>ff>45
into
json output:
[
{
"type" : "pie",
"name" : "website",
"data" : [
[
"ot",
4
],
[
"om",
6
],
[
"we",
34
]
]
}
]
I have updated the answer please check the json part, I would like the php code.
regards
You can explode() on the >s, and then loop through the elements:
$string = "ot>4>om>6>we>34>ff>45";
$array1 = [
'name'=>'website',
'data'=>[]
]
$array2 = [
'name'=>'websitedata',
'data'=>[]
]
foreach(explode('>', $string) as $index => $value){
if($index & 1) //index is odd
$array2['data'][] = $value;
else //index is even
$array1['data'][] = $value;
}
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
A solution using preg_match_all():
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$array1 = [
'name'=>'website',
'data'=> $matches[1]
];
$array2 = [
'name'=>'websitedata',
'data'=> $matches[2]
];
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
Update:
To get the second type of array you wanted, use this:
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$data = [];
foreach($matches[1] as $index => $value){
if(isset($matches[2][$index]))
$data[] = '["' . $value . '",' . $matches[2][$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
Update #2:
This code uses explode(), and although it's probably not the most efficient way of doing it, it works.
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
$keys = [];
$values = [];
foreach(explode('>', $string) as $key => $value){
if(!($key & 1)) //returns true if the key is even, false if odd
$keys[] = $value;
else
$values[] = $value;
}
$data = [];
foreach($keys as $index => $value){
if(isset($values[$index]))
$data[] = '["' . $value . '",' . $values[$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
This should work, though there are probably better ways to do it.
$string = "ot>4>om>6>we>34>ff>45";
$website = ["name" => "website", "data" => []];
$websiteData = ["name" => "websitedata", "data" => []];
foreach(explode(">", $string) as $i => $s) {
if($i % 2 === 0) {
$website["data"][] = $s;
} else {
$websiteData["data"][] = $s;
}
}
echo json_encode($website);
echo json_encode($websiteData);
A regex alternative:
preg_match_all("/([a-z]+)>(\d+)/", $string, $matches);
$website = ["name" => "website", "data" => $matches[1]];
$websiteData = ["name" => "websitedata", "data" => $matches[2]];
Try this code:
$string = 'ot>4>om>6>we>34>ff>45';
$string_split = explode('>', $string);
$data = array("name" => "website");
$data2 = $data;
foreach ($string_split as $key => $value)
{
if (((int)$key % 2) === 0)
{
$data["data"][] = $value;
}
else
{
$data2["data"][] = $value;
}
}
$json1 = json_encode($data, JSON_NUMERIC_CHECK);
$json2 = json_encode($data2, JSON_NUMERIC_CHECK);
echo $json1;
echo $json2;
Output:
{"name":"website","data":["ot","om","we","ff"]}
{"name":"website","data":[4,6,34,45]}
Regards.
Try this snippet:
$strings = explode('>', 'ot>4>om>6>we>34>ff>45');
// print_r($string);
$x = 0;
$string['name'] = 'website';
$numbers['name'] = 'websitedata';
foreach ($strings as $s)
{
if ($x == 0) {
$string['data'][] = $s;
$x = 1;
} else {
$numbers['data'][] = $s;
$x = 0;
}
}
print_r(json_encode($string));
echo "<br/>";
print_r(json_encode($numbers));
As usual - it is long winded but shows all the steps to get to the required output.
<?php //https://stackoverflow.com/questions/27822896/need-help-php-to-json-array
// only concerned about ease of understnding not code size or efficiency.
// will speed it up later...
$inString = "ot>4>om>6>we>34>ff>45";
$outLitRequired = '[{"name":"website","data":["ot","om","we","ff"]}]';
$outValueRequired = '[{"name":"websitedata","data":["4","6","34","45"]}]';
// first: get a key / value array...
$itemList = explode('>', $inString);
/* debug */ var_dump(__FILE__.__LINE__, $itemList);
// outputs ------------------------------------
$outLit = array();
$outValue = array();
// ok we need to process them in pairs - i like iterators...
reset($itemList); // redundant but is explicit
// build both output 'data' lists
while (current($itemList)) {
$outLit[] = current($itemList);
next($itemList); // advance the iterator.
$outValue[] = current($itemList);
next($itemList);
}
/* debug */ var_dump(__FILE__.__LINE__, $itemList, $outLit, $outValue);
// make the arrays look like the output we want...
// we need to enclose them as arrays to get the exact formatting required
// i do that in the 'json_encode' statements.
$outLit = array('name' => 'website', 'data' => $outLit);
$outValue = array('name' => 'websitedata', 'data' => $outValue);
// convert to JSON.
$outLitJson = json_encode(array($outLit));
$outValueJson = json_encode(array($outValue));
// show required and calculated values...
/* debug */ var_dump(__FILE__.__LINE__, 'OutLit', $outLitRequired, $outLitJson);
/* debug */ var_dump(__FILE__.__LINE__, 'OutValue', $outValueRequired, $outValueJson);

Create array nested PHP

Hi all' I have a page into PHP where I retrieve XML data from a server and I want to store this data into an array.
This is my code:
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
array_push($hotel_array, $hotel_array2);
}
}
In this mode I have the array hotel_array which all hotel with rooms.
The problem is that: into my XML I can have multiple hotel with same ID (the same hotel) with same information but different rooms.
If I have an hotel that I have already inserted into my hotel_array I don't want to insert a new array inside it but I only want to take its rooms array and insert into the exisiting hotel.
Example now my situation is that:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
id = 1
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
[0]{
id = 1,
name = 'test'
rooms{
id = 30
}
}
}
I'd like to have this result instead:
hotel_array{
[0]{
id = 1,
name = 'test'
rooms{
[0]{
id = 1
}
[1]{
id = 30
}
}
}
[0]{
id = 2,
name = 'test2'
rooms{
id = 100
}
}
}
How to create an array like this?
Thanks
first thing is it helps to keep the hotel id as the index on hotel_array when your creating it.
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string)$entry2->attributes()->HOTEL_CODE;
$hotel_array2 = array();
$hotel_array2['id'] = $entry2->ID;
$hotel_array2['name'] = utf8_decode($entry2->HOTEL_NAME);
$i=0;
foreach($entry2->ROOM_DATA as $room){
$room_array = array();
$room_array['id'] = (string)$room->attributes()->CCHARGES_CODE;
$hotel_array2['rooms'][$i] = array($room_array);
$i++;
}
if (!isset($hotel_array[$hotel_array2['id']])) {
$hotel_array[$hotel_array2['id']] = $hotel_array2;
} else {
$hotel_array[$hotel_array2['id']]['rooms'] = array_merge($hotel_array[$hotel_array2['id']]['rooms'], $hotel_array2['rooms']);
}
}
}
Whilst this is the similar answer to DevZer0 (+1), there is also quite a bit that can be done to simplify your workings... there is no need to use array_merge for one, or be specific about $i within your rooms array.
$hotels = array();
foreach ($xml->DATA as $entry){
foreach ($entry->HOTEL_DATA as $entry2){
$id = (string) $entry2->attributes()->HOTEL_CODE;
if ( empty($hotels[$id]) ) {
$hotels[$id] = array(
'id' => $id,
'name' => utf8_decode($entry2->HOTEL_NAME),
'rooms' => array(),
);
}
foreach($entry2->ROOM_DATA as $room){
$hotels[$id]['rooms'][] = array(
'id' => (string) $room->attributes()->CCHARGES_CODE;
);
}
}
}
Just in case it helps...
And this :)
$hotel_array = array();
foreach ($xml->DATA as $entry)
{
foreach ($entry->HOTEL_DATA as $entry2)
{
$hotel_code = (string) $entry2->attributes()->HOTEL_CODE;
if (false === isset($hotel_array[$hotel_code]))
{
$hotel = array(
'id' => $entry2->ID,
'code' => $hotel_code,
'name' => utf8_decode($entry2->HOTEL_NAME)
);
foreach($entry2->ROOM_DATA as $room)
{
$hotel['rooms'][] = array(
'id' => (string)$room->attributes()->CCHARGES_CODE,
);
}
$hotel_array[$hotel_code] = $hotel;
}
}
}

Display correct data from .json file

I apologise in advance if this is vague, I have battled with this for nigh on 10 hours now and have got nowhere...
My client has been screwed over by their SEO company and I am trying to help to save their business. One major problem we have is that theirs websites content is dependant on a data feed hosted on their SEO companys website. The content for different areas around their main town is auto generated by this script. Part of the script is hosted on the clients server and this communicates with the feed.
I have found a JSON file with all the data that the feed uses, but am struggling to get the script to read off of this file instead.
There appears to be 2 functions I should be interested in generateContentFromFeed and generateTextFromFile. Currently it appears to be using generateContentFromFeed (but may be using generateTextFromFile elsehwere, but I'm quite sure it isnt. I believe this function is there if you dont want to get the data externally).
I have tried swapping the functions around, and changing the source of the feed in the config file, but with no joy. All this achieved was outputting the entire contents of the json file.
Files are below:
content.class.php
<?php
/**
* This class manipulates content from files / JSON into an array
* Also includes helpful functions for formatting content
*/
class Content {
public $links = array();
public $replacements = array();
private function stripslashes_gpc($string) {
if (get_magic_quotes_gpc()) {
return stripslashes($string);
} else {
return $string;
}
}
private function sourceContentToArray($source) {
// array
if (is_array($source)) {
$array = $source;
// json
} elseif (json_decode($source) != FALSE || json_decode($source) != NULL) {
$array = json_decode($source, 1);
// file
} elseif (file_exists($source)) {
if (!$array = json_decode(file_get_contents($source), 1)) {
echo "File empty or corrupt";
return false;
}
} else {
echo 'Source content not recognised';
return false;
}
return $array;
}
public function generateContent($source, $type="paragraph", $label="", $subject, $num=0, $randomize_order=false) {
if (!$array = $this->sourceContentToArray($source))
return false;
$array = empty($this->links) ? $this->loadLinks($array, $subject) : $array;
$this->loadGlobalReplacements($array, $subject);
$ca = array();
foreach ($array['content'] as $c) {
if ($c['type'] == $type) {
if (empty($label) || (!empty($label) && $c['label'] == $label)) {
$ca[] = $c;
}
}
}
$rc = array();
foreach ($ca as $k => $a) {
$rc[] = $this->randomizeContent($a, $subject.$k);
}
if ((!is_array($num) && $num >= 1) || (is_array($num) && $num[0] >= 1)) {
$rc = $this->arraySliceByInteger($rc, $subject, $num);
} else if ((!is_array($num) && $num > 0 && $num < 1) || (is_array($num) && $num[0] > 0 && $num[0] < 1)) {
$rc = $this->arraySliceByPercentage($rc, $subject, $num);
} else {
if ($randomize_order == true)
$rc = $this->arraySliceByPercentage($rc, $subject, 1);
}
return $rc;
}
public function formatContent($source, $type, $subject, $find_replace=array()) {
$c = "";
foreach ($source as $k => $s) {
$text = "";
if ($type == "list" || $type == "paragraph") {
$text .= "<h3>";
foreach ($s['title'] as $t) {
$text .= $t." ";
}
$text .= "</h3>";
}
if ($type == "list") {
$text .= "<ul>";
} else if ($type == "paragraph") {
$text .= "<p>";
}
foreach ($s['parts'] as $b) {
if ($type == "list")
$text .= "<li>";
$text .= $b." ";
if ($type == "list")
$text .= "</li>";
}
if ($type == "list") {
$text .= "</ul>";
} else if ($type == "paragraph") {
$text .= "</p>";
}
$text = $this->findReplace($s['replacements'], $text, $subject.$k."1");
$text = $this->injectLinks($this->links, $text, $subject.$k."2");
$text = $this->findReplace($this->replacements, $text, $subject.$k."3");
$text = $this->findReplace($find_replace, $text, $subject.$k."4");
$text = $this->aAnReplacement($text);
$text = $this->capitaliseFirstLetterOfSentences($text);
$c .= $this->stripslashes_gpc($text);
}
return $c;
}
public function injectLinks($links, $text, $subject) {
global $randomizer;
if (empty($links))
return $text;
foreach ($links as $k => $link) {
$_link = array();
if (preg_match("/\{L".($k+1)."\}/", $text)) {
preg_match_all("/\{L".($k+1)."\}/", $text, $vars);
foreach ($vars[0] as $vark => $varv) {
$_link['link'] = empty($_link['link']) ? $this->links[$k]['link'] : $_link['link'];
$l_link = $randomizer->fetchEncryptedRandomPhrase($_link['link'], 1, $subject.$k.$vark);
unset($_link['link'][array_search($l_link, $_link['link'])]);
$_link['link'] = array_values($_link['link']);
$_link['text'] = empty($_link['text']) ? $this->links[$k]['text'] : $_link['text'];
$l_text = $randomizer->fetchEncryptedRandomPhrase($_link['text'], 2, $subject.$k.$vark);
unset($_link['text'][array_search($l_text, $_link['text'])]);
$_link['text'] = array_values($_link['text']);
$link_html = empty($l_link) ? $l_text : "".$l_text."";
$text = preg_replace("/\{L".($k+1)."\}/", $link_html, $text, 1);
$this->removeUsedLinksFromPool($l_link);
}
}
}
return $text;
}
private function loadLinks($source, $subject) {
global $randomizer;
if (!empty($source['links'])) {
foreach ($source['links'] as $k => $l) {
$source['links'][$k]['link'] = preg_split("/\r?\n/", trim($l['link']));
$source['links'][$k]['text'] = preg_split("/\r?\n/", trim($l['text']));
}
$this->links = $source['links'];
}
return $source;
}
private function loadGlobalReplacements($source, $subject) {
global $randomizer;
$source['replacements'] = $this->removeEmptyIndexes($source['replacements']);
foreach ($source['replacements'] as $k => $l) {
$source['replacements'][$k] = preg_split("/\r?\n/", trim($l));
}
$this->replacements = $source['replacements'];
return $source;
}
private function removeUsedLinksFromPool($link) {
foreach ($this->links as $key => $links) {
foreach ($links['link'] as $k => $l) {
if ($l == $link) {
unset($this->links[$key]['link'][$k]);
}
}
}
}
private function randomizeContent($source, $subject) {
global $randomizer;
$source['title'] = $this->removeEmptyIndexes($source['title']);
foreach ($source['title'] as $k => $t) {
$source['title'][$k] = trim($randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", trim($t)), 1, $subject.$k));
}
$source['parts'] = $this->removeEmptyIndexes($source['parts']);
foreach ($source['parts'] as $k => $b) {
$source['parts'][$k] = trim($randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", trim($b)), 2, $subject.$k));
}
$source['structure'] = trim($source['structure']);
if ($source['type'] == "list") {
$source['parts'] = array_values($source['parts']);
$source['parts'] = $randomizer->randomShuffle($source['parts'], $subject."9");
} else if ($source['structure'] != "") {
$source['structure'] = $randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", $source['structure']), 3, $subject);
preg_match_all("/(\{[0-9]{1,2}\})/", $source['structure'], $matches);
$sc = array();
foreach ($matches[0] as $match) {
$sc[] = str_replace(array("{", "}"), "", $match);
}
$bs = array();
foreach ($sc as $s) {
$bs[] = $source['parts'][$s];
}
$source['parts'] = $bs;
}
$source['replacements'] = $this->removeEmptyIndexes($source['replacements']);
foreach ($source['replacements'] as $k => $r) {
$source['replacements'][$k] = preg_split("/\r?\n/", trim($r));
}
return $source;
}
private function removeEmptyIndexes($array, $reset_keys=false) {
foreach($array as $key => $value) {
if ($value == "") {
unset($array[$key]);
}
}
if (!empty($reset_keys))
$array = array_values($array);
return $array;
}
private function arraySliceByPercentage($array, $subject, $decimal=0.6) {
global $randomizer;
$array = $randomizer->randomShuffle($array, $subject);
if (is_array($decimal))
$decimal = $randomizer->fetchEncryptedRandomPhrase(range($decimal[0], $decimal[1], 0.1), 1, $subject);
$ac = count($array);
$n = ceil($ac * $decimal);
$new_array = array_slice($array, 0, $n);
return $new_array;
}
private function arraySliceByInteger($array, $subject, $number=10) {
global $randomizer;
$array = $randomizer->randomShuffle($array, $subject);
if (is_array($number))
$number = $randomizer->fetchEncryptedRandomPhrase(range($number[0], $number[1]), 1, $subject);
$new_array = array_slice($array, 0, $number);
return $new_array;
}
private function aAnReplacement($text) {
$irregular = array(
"hour" => "an",
"europe" => "a",
"unique" => "a",
"honest" => "an",
"one" => "a"
);
$text = preg_replace("/(^|\W)([aA])n ([^aAeEiIoOuU])/", "$1$2"." "."$3", $text);
$text = preg_replace("/(^|\W)([aA]) ([aAeEiIoOuU])/", "$1$2"."n "."$3", $text);
foreach ($irregular as $k => $v) {
if (preg_match("/(^|\W)an? ".$k."/i", $text)) {
$text = preg_replace("/(^|\W)an? (".$k.")/i", "$1".$v." "."$2", $text);
}
}
return $text;
}
private function capitaliseFirstLetterOfSentences($text) {
$text = preg_replace("/(<p>|<li>|^|[\n\t]|[\.\?\!]+\s)(<a.*?>)?(?!%)([a-z]{1})/se", "'$1$2'.strtoupper('$3')", $text);
return $text;
}
public function findReplace($find_replace, $input, $subject) {
global $randomizer;
if (!empty($find_replace)) {
foreach ($find_replace as $key => $val) {
if (is_array($val)) {
$fr = $val;
$pattern = "/".preg_quote($key)."/i";
preg_match_all($pattern, $input, $vars);
foreach ($vars[0] as $vark => $varv) {
$fr = empty($fr) ? $val : $fr;
$new_val = $randomizer->fetchEncryptedRandomPhrase($fr, 1, $subject.$key.$vark);
unset($fr[array_search($new_val, $fr)]);
$fr = array_values($fr);
$input = preg_replace($pattern, $new_val, $input, 1);
}
} else {
$pattern = "/".preg_quote($key)."/i";
$input = preg_replace($pattern, $val, $input);
}
}
}
return $input;
}
public function generateTextFromFile($file, $subject, $find_replace=array()) {
global $randomizer;
$content = trim(file_get_contents($file));
$lines = preg_split("/\r?\n/s", $content);
$text = $randomizer->fetchEncryptedRandomPhrase($lines, 4, $subject);
$text = $this->findReplace($find_replace, $text, $subject);
return $text;
}
public function generateContentFromFeed($file, $type, $label="", $subject, $num=0, $find_replace=array()) {
global $cfg;
$vars = array ( "api_key" => $cfg['feed']['api_key'],
"subject" => $subject,
"file" => $file,
"type" => $type,
"label" => $label,
"num" => $num,
"find_replace" => json_encode($find_replace));
$encoded_vars = http_build_query($vars);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://feeds.redsauce.com/example/index.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
}
?>
config.php
<?php
// LOCAL SERVER
// Paths
$cfg['basedir'] = "public_html/directory/"; // change this for inlcudes and requires.
$cfg['baseurl'] = "/directory/"; // change this for relative links and linking to images, media etc.
$cfg['fullbaseurl'] = "http://customerssite.com/directory/"; // change this for absolute links and linking to pages
/*
// Database - local
$cfg['database']['host'] = "127.0.0.1";
$cfg['database']['name'] = "username";
$cfg['database']['user'] = 'root'; // change this to the database user
$cfg['database']['password'] = ''; // change this to the database password
*/
// Database - web
$cfg['database']['host'] = "localhost";
$cfg['database']['name'] = "db";
$cfg['database']['user'] = 'user'; // change this to the database user
$cfg['database']['password'] = 'pass'; // change this to the database password
// Errors
$cfg['errors']['display'] = 1; // change this to display errors on or off (on for testing, off for production)
$cfg['errors']['log'] = 0; // change this to log errors to /log/error.log
// Caching
$cfg['caching']['status'] = 0; // determines whether the cache is enabled. 1 for enabled, 0 for disabled
$cfg['caching']['expiry_time'] = 604800; // determines expiry time of cached items (604800 = 14 days)
$cfg['caching']['directory'] = $cfg['basedir']."public_html/_cache/"; // directory in which cached files are stored
// Analytics
$cfg['analytics']['status'] = 1;
$cfg['analytics']['tracking_id'] = "UA-21030138-1";
// Javascript
$cfg['maps']['status'] = 0; // load google maps javascript
$cfg['jquery_ui']['status'] = 0; // load jquery ui javascript + css
// Site defaults
$cfg['site_name'] = "Customer"; // change this to the site name
$cfg['default']['page_title'] = "Customer"; // change this to the default title of all pages
$cfg['default']['page_description'] = "Customer"; // change this to the default meta-description of all pages
$cfg['default']['email'] = "Customer"; // change this to the administrators email for receiving messages when users signup etc
$cfg['default']['category']['id'] = 130;
// Email
$cfg['email']['address'] = "Customer"; // change this to the administrators email for receiving messages when users signup etc
$cfg['email']['from'] = $cfg['site_name']." <Customer>"; // email will appear to have come from this address
$cfg['email']['subject'] = "Enquiry from ".$cfg['site_name']; // subject of the email
$cfg['email']['success_message'] = "Thank you for your enquiry. Someone will be in touch with you shortly."; // message to display if the email is sent successfully
$cfg['email']['failure_message'] = "There was an error processing your enquiry. Please try again."; // message to display if the email is not sent successfully
// Content feed
$cfg['feed']['api_key'] = "Customer"; // enter the unique content feed api key here
$cfg['feed']['url'] = "http://feeds.customersseocompany.com/customer/index.php"; // URL to connect to to pull the content feed
// Dates
date_default_timezone_set('Europe/London');
$cfg['default']['date_format'] = "d/m/Y H:i:s";
// Options
$cfg['listings']['type'] = "ajax"; // options are none (to display no listings), page (to display the listings on the page) or ajax (to load the listings via AJAX)
$cfg['listings']['num_per_page'] = 10; // maximum number of listings to show per page
// Routing
$cfg['routes'] = array(
'category' => array(
"(?P<category>.+?)-category",
"_pages/category.php"
),
't1' => array(
"(?P<category>.+?)-in-(?P<t1_name>.+?)_(?P<county>.+)",
"_pages/tier1.php"
),
't1_map' => array(
"t1-map-data-(?P<t1_name>.+)-(?P<page_num>[0-9]+)",
"_ajax/map-data.php"
),
't2_map' => array(
"t2-map-data-(?P<t2_name>.+)-(?P<t1_name>.+)-(?P<page_num>[0-9]+)",
"_ajax/map-data.php"
),
'ajax_listings' => array(
"ajax-listings-(?P<category>.+?)-(?P<t2_id>.+)-(?P<page_num>[0-9]+)",
"_ajax/listings.php"
),
'search' => array(
"^search\/?$",
"_pages/search.php"
),
'single' => array(
".*?-(?P<listing_id>[0-9]+)",
"_pages/single.php"
)
);
// Site specific
// Encoding
header('Content-type: text/html; charset=UTF-8');
?>
part of the code used in tier1.php (file used to generate each location and keywords page) which generates the paragraph text :
<?php
$randParas = array(1, 2, 3);
$numParas = $randomizer -> fetchEncryptedRandomPhrase($randParas, 1, $_SERVER['REQUEST_URI']);
$content = $content->generateContentFromFeed(
// file
"categories/".$category[0]['category_slug']."/paragraphs",
// type
"paragraph",
// label
"",
// subject
$_SERVER['REQUEST_URI']."7",
// num
$numParas,
// find_ replace
array(
"XX" => $t1_location[0]['definitive_name'],
"YY" => $cfg['site_name']
)
);
?>
A snippet from one of the json files (I am aware the code I have pasted terminates early, I just wanted to put a part of it here as the file is huge!):
{"filename":" xx keywords","content":[{"title":{"1":"xx example\r\nexample in xx\r\nexample in the xx region\r\nexample in the xx area","2":"","3":"","4":""},"type":"paragraph","label":"","structure":"","parts":{"1":"Stylish and practical, a xx keyword \r\nPractical and stylish, a xx keyword \r\nUseful and pragmatic, a xx keyword \r\nPragmatic and useful, a xx keyword \r\nModern and convenient, a xx keyword ",
If you need any more info, please tell me what you need. I really appreciate the help in advance, as I really want to help this client out. They are great people who do not deserve to be hit by a negative SEO company.
What would be the most helpful is if somebody knows what this script is! I can then buy/download it and generate my own feed using the data.
If you can help with either the code to generate the feed, or how I should go about getting the data out of the json files and filter it correctly, that would be great!
Many thanks,
Kevin
ps. Sorry for all the code, I have been told off before for not posting enough!
EDIT : Here is the code I am now using after the suggestion below:
<?php
$randParas = array(1, 2, 3);
$numParas = $randomizer -> fetchEncryptedRandomPhrase($randParas, 1, $_SERVER['REQUEST_URI']);
$content = $content->generateContent(
// file
"content/categories/".$category[0]['category_slug']."/paragraphs.json",
// type
"paragraph",
// label
"",
// subject
$_SERVER['REQUEST_URI']."7",
// num
$numParas,
// find_ replace
array(
"XX" => $t1_location[0]['definitive_name'],
"YY" => $cfg['site_name']
)
);
?>
<?php
if($numParas == '3'){
$divClass = 'vertiCol';
}
elseif($numParas == '2'){
$divClass = 'vertiColDub';
}
else {
$divClass = 'horizCol';
}
$randImages = glob('_images/categories/'.$category[0]['category_slug'].'/*.jpg');
$randImages = $randomizer->randomShuffle($randImages, $_SERVER['REQUEST_URI']);
$fc = preg_replace("/<h3>.*?<\/h3>/", "$0", $content);
$fc = preg_replace("/<h3>.*?<\/h3><p>.*?<\/p>/", "<div class=\"contCol ".$divClass."\">$0$1</div>", $content);
$fca = preg_split("/(\.|\?|\!)/", $fc, -1, PREG_SPLIT_DELIM_CAPTURE);
$prStr = '';
foreach ($fca as $fck => $fcv) {
if ($fck % 3 == 0 && $fck != 0 && !in_array($fcv, array(".", "?", "!")))
$prStr .= "</p>\n<p>";
$prStr .= $fcv;
}
preg_match_all('/<div class="contCol '.$divClass.'"><h3>.*?<\/h3>.*?<\/div>/s', $prStr, $matches);
$randAlign = array(
array('topleft'),
array('topright'),
#array('bottomleft'),
# array('bottomright')
);
$i=0;
$randSelectAlign = $randomizer->fetchEncryptedRandomPhrase($randAlign, 0, $_SERVER['REQUEST_URI']);
$randSelectAlign = $randSelectAlign[0];
foreach($matches[0] as $newPar){
$i++;
if($randSelectAlign=='topleft'){
echo str_replace('</h3><p>', '</h3><p><span class="imgWrap" style="float:left"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span>', $newPar);
}
elseif($randSelectAlign=='topright'){
echo str_replace('</h3><p>', '</h3><p><span class="imgWrap" style="float:right"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span>', $newPar);
}
elseif($randSelectAlign=='bottomleft'){
echo str_replace('</p></div>', '<span class="imgWrap" style="float:left"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span></div>', $newPar);
}
elseif($randSelectAlign=='bottomright'){
echo str_replace('</p></div>', '<span class="imgWrap" style="float:right"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span></div>', $newPar);
}
else {
}
//randomly from float array based on server uri!
//randomly select a way to display the images here etc
#
}
?>
Which is giving me the following error messages:
Notice: Array to string conversion in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 230
Notice: Array to string conversion in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 231
Warning: preg_split() expects parameter 2 to be string, array given in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 233
Warning: Invalid argument supplied for foreach() in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 237
These lines of code are :
230 $fc = preg_replace("/<h3>.*?<\/h3>/", "$0", $content);
231 $fc = preg_replace("/<h3>.*?<\/h3><p>.*?<\/p>/", "<div class=\"contCol ".$divClass."\">$0$1</div>", $content);
233 $fca = preg_split("/(\.|\?|\!)/", $fc, -1, PREG_SPLIT_DELIM_CAPTURE);
235 $prStr = '';
237 foreach ($fca as $fck => $fcv) {
if ($fck % 3 == 0 && $fck != 0 && !in_array($fcv, array(".", "?", "!")))
$prStr .= "</p>\n<p>";
$prStr .= $fcv;
}
I presume this is because its spitting the content out as an array? Is there anything in particular I need to do to the data to make it output correctly?
Many thanks,
Kevin
Having glanced over the code, I think I have some idea what it's supposed to do, though I'm still confused about the randomizer stuff ;-)
You can pass your JSON data as a string into the generateContent() method as the first parameter ($source).
The generateContent() returns an array, so you will have to run it through formatContent() (I think).

php, mysql, arrays - how to get the row name

I have the following code
while($row = $usafisRSP->fetch_assoc()) {
$id = $row['id'];
$Applicantid = $row['Applicantid'];
$unique_num = $row['unique_num'];
// .................
$hidden_fields = array($Applicantid, $unique_num, $regs_t ....);
$hidden_values = array();
foreach ($hidden_fields as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
}
and the result is something like this
0 = 116153840
1 = 136676636
2 = 2010-12-17T04:12:37.077
3 = XQ376
4 = MUKANTABANA
I would like to replace 0, 1, 2, 3 etc with some custom values like "Id", "application name" to make the result like
id = 116153840
application name = 136676636
etc ..
how can I do that ?
Replace the $hidden_fields = array(... line with the following:
$hidden_keys = array('id', 'Applicantid', 'unique_num');
$hidden_fields = array_intersect_key($row, array_fill_keys($hidden_keys, NULL));
If you want to suppress all fields with value 0, either use
$hidden_fields = array_filter($hidden_fields, function($v) {return $v != 0;});
(this will completely omit the 0-entries) or
$hidden_fields = array_map($hidden_fields, function($v) {return ($v==0?'':$v);});
(this will leave them blank). If you're using an older version than 5.3, you'll have to replace the anonymous functions with calls to create_function.
I assume not every field in your row should be a hidden field. Otherwise you could just do $hidden_fields = $row.
I would create an array that specifies the hidden fields:
$HIDDEN = array(
'id' => 'Id',
'Applicantid' => 'application name',
'unique_num' => 'whatever'
);
And then in your while loop:
while(($row = $usafisRSP->fetch_assoc())){
$hidden_fields = array();
foreach$($HIDDEN as $field=>$name) {
$hidden_fields[$name] = $row[$field];
}
//...
foreach($hidden_fields as $name => $value) {
$hidden_fields[$name] = $name . ' = ' . base64_decode($value);
echo $hidden_values[$name];
// or just echo $name, ' = ',$hidden_fields[$value];
}
}
foreach ($row as $key => $value) {
$hidden_values[$value] = "$key = ".base64_decode($value)."<br>";
echo $hidden_values[$value];
}
This could give you something relevant. Through accessing the string keys from the row array which contains the string keys

Categories