If i execute var_dump(array($output)) is shows
array(1) { [0]=> string(573) " __(Developer’s Must Have Gray Cardigan|:89.77,gravityforms), __(Polka Dots Blue Dress|:55.45,gravityforms), __(Classic Brown Leather Bag with Orange Details|:66.84,gravityforms), __(Cycling Pack Steel Blue|:360.00,gravityforms), __(Classic Brown Leather Bag with Orange Details|:,gravityforms), __(The Black Cat Winter Jacket|:254.45,gravityforms), __(Split Slit Gold Threading Cardi|:165.74,gravityforms), __(Slim Fit Pants|:85,gravityforms), __(Get the Complete WordPress Developer Outfit|:65.55,gravityforms), __(Biodiesel Cardigan Dreamcatcher|:175.00,gravityforms)," }
But i want to like this
array(10) { [0]=> string(44) "Developer’s Must Have Gray Cardigan|:89.77" [1]=> string(28) "Polka Dots Blue Dress|:55.45" [2]=> string(52) "Classic Brown Leather Bag with Orange Details|:66.84" [3]=> string(31) "Cycling Pack Steel Blue|:360.00" [4]=> string(47) "Classic Brown Leather Bag with Orange Details|:" [5]=> string(35) "The Black Cat Winter Jacket|:254.45" [6]=> string(39) "Split Slit Gold Threading Cardi|:165.74" [7]=> string(18) "Slim Fit Pants|:85" [8]=> string(50) "Get the Complete WordPress Developer Outfit|:65.55" [9]=> string(39) "Biodiesel Cardigan Dreamcatcher|:175.00" }
how can i do this?
Use array_push
$outputArr = array();
if ($loop->have_posts()) {
while ($loop->have_posts()) {
$loop->the_post();
$price = get_post_meta(get_the_ID(), '_regular_price', true);
array_push($outputArr, ' __(' . get_the_title() . '|:' . $price . ',gravityforms)');
}
}
var_dump($outputArr);
Hope this helps
If you want use this array further make foreach and execute
Code
$l = array(
" __(Developer’s Must Have Gray Cardigan|:89.77,gravityforms), __(Polka Dots Blue Dress|:55.45,gravityforms), __(Classic Brown Leather Bag with Orange Details|:66.84,gravityforms), __(Cycling Pack Steel Blue|:360.00,gravityforms), __(Classic Brown Leather Bag with Orange Details|:,gravityforms), __(The Black Cat Winter Jacket|:254.45,gravityforms), __(Split Slit Gold Threading Cardi|:165.74,gravityforms), __(Slim Fit Pants|:85,gravityforms), __(Get the Complete WordPress Developer Outfit|:65.55,gravityforms), __(Biodiesel Cardigan Dreamcatcher|:175.00,gravityforms),"
);
$m = explode('__', $l[0]);
$n = array();
array_walk($m, function ($x, $y) use (&$n) {
$w = trim(preg_replace('/,(|\s+)$/', '', $x));
$n[] = ($w) ? '__'.$w : '';
});
$result = array_slice(array_filter($n), 0);
var_dump($result);
Output
Edit
Or you can just use this
$l = array(
" __(Developer’s Must Have Gray Cardigan|:89.77,gravityforms), __(Polka Dots Blue Dress|:55.45,gravityforms), __(Classic Brown Leather Bag with Orange Details|:66.84,gravityforms), __(Cycling Pack Steel Blue|:360.00,gravityforms), __(Classic Brown Leather Bag with Orange Details|:,gravityforms), __(The Black Cat Winter Jacket|:254.45,gravityforms), __(Split Slit Gold Threading Cardi|:165.74,gravityforms), __(Slim Fit Pants|:85,gravityforms), __(Get the Complete WordPress Developer Outfit|:65.55,gravityforms), __(Biodiesel Cardigan Dreamcatcher|:175.00,gravityforms),"
);
$n = explode(', ', $l[0]);
Related
I try to write a file on my server, but I don't understand what's happening : it's always empty (blank page).
There is no error thrown.
When I insert inside the loop a var_dump($lines), I see the data but at the moment an error appear
With the code below
$minLat = -3.0000; //41.34343606848294;
$maxLat = 22.0000; //57.844750992891;
$minLng = -0.0300; //-16.040039062500004;
$maxLng = 90.4200; //29.311523437500004;
$step = 0.1;
$k = 1;
$estimator = new KNearestNeighbors(9);
$estimator->train($dataset->getSamples(), $dataset->getTargets());
$lines = [];
for($lat=$minLat; $lat<$maxLat; $lat+=$step) {
for($lng=$minLng; $lng<$maxLng; $lng+=$step) {
$lines[] = sprintf('%s;%s;%s', $lat, $lng, $estimator->predict([[$lat, $lng]])[0]);
}
}
var_dump($lines); ==> display info, but always empty
$filename = '/var/www/test/php-ml/result_map.csv';
//$content = implode(PHP_EOL, $lines);
$content = implode( "\n", $lines );
file_put_contents($filename, $content);
the result (example)
-------------
bool(true) ==> check if the file exist
array(1) { [0]=> string(41) "-3;-0.03;Apple 15 Inch MacBook Pro Laptop" }
array(2) { [0]=> string(41) "-3;-0.03;Apple 15 Inch MacBook Pro Laptop" [1]=> string(40) "-3;0.07;Apple 15 Inch MacBook Pro Laptop" }
array(3) { [0]=> string(41) "-3;-0.03;Apple 15 Inch MacBook Pro Laptop" [1]=> string(40) "-3;0.07;Apple 15 Inch MacBook Pro Laptop" [2]=> string(40) "-3;0.17;Apple 15 Inch MacBook Pro Laptop" }
array(4) { [0]=> string(41) "-3;-0.03;Apple 15 Inch MacBook Pro Laptop" [1]=> string(40) "-3;0.07;Apple 15 Inch MacBook Pro Laptop" [2]=> string(40) "-3;0.17;Apple 15 Inch MacBook Pro Laptop" [3]=> string(40) "-3;0.27;Apple 15 Inch MacBook Pro Laptop" }
I am trying to create a project which will help students study various areas. The idea is that I have a piece of raw text, which contains quiz questions and answers which I want to parse as question header and answer options, which will be inserted into a database. However, the text is not properly formatted and due to the large amount of questions and answers (around ~20k per total), I cannot afford the time to manually insert them or format the text myself.
The raw text looks like this:
1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50
I tried creating my own PHP functions to parse the text properly, however I cannot get myself to get past the random line breaks, spaces, etc.
What I am trying to obtain:
array(1) {
[0]=>
array(3) {
["questionNumber"]=>
string(1) "1"
["questionText"]=>
string(175) "A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?"
["options"]=>
array(5) {
["a"]=>
string(6) "$44.44"
["b"]=>
string(7) "$109.08"
["c"]=>
string(7) "$118.80"
["d"]=>
string(7) "$408.04"
["e"]=>
string(7) "$444.40"
}
}
}
The code I have so far:
$rawText = '1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50
';
$rawTextLines = explode("\n", $rawText);
foreach ($rawTextLines as $lineNumber => $lineContents) {
$lContents = trim($lineContents);
if (empty ($lContents)) {
unset ($rawTextLines[$lineNumber]);
} else {
$rawTextLines[$lineNumber] = $lContents;
}
}
$processedQuestions = array ();
$currentQuestionHeader = 0;
foreach ($rawTextLines as $lineNumber => $lineContents) {
if (ctype_digit(substr($lineContents, 0, 1))) { // Question header
$questionHeaderInformation = explode('.', $lineContents);
$currentQuestionHeader = $questionHeaderInformation[0];
$processedQuestions[$currentQuestionHeader]['questionNumber'] = $currentQuestionHeader;
$processedQuestions[$currentQuestionHeader]['questionText'] = $questionHeaderInformation[1];
} else { // Question option
$options = explode(')', $lineContents);
if (count ($options) % 2 === 0) {
$processedQuestions[$currentQuestionHeader]['options'][trim($options[0])] = ucfirst(trim($options[1]));
} else {
}
}
}
Which produces this:
array(2) {
[1]=>
array(3) {
["questionNumber"]=>
string(1) "1"
["questionText"]=>
string(35) " A car averages 27 miles per gallon"
["options"]=>
array(1) {
["a"]=>
string(8) "$44.44 b"
}
}
[2]=>
array(3) {
["questionNumber"]=>
string(1) "2"
["questionText"]=>
string(96) " When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?"
["options"]=>
array(3) {
["a"]=>
string(1) "4"
["b"]=>
string(2) "14"
["c"]=>
string(2) "16"
}
}
}
As you can see, the current output does not match - not by far, what I am trying to obtain.
Thank you in advance.
Hellow,
^[0-9]+\. (.*)[\r\n]+a\)[\s]+(.*)[\s]+b\)[\s]+(.*)[\s]+c\)[\s]+(.*)[\s]+d\)[\s]+(.*)[\s]+e\)[\s]+(.*)[\s]*
Try it !
$re = '/^[0-9]+\. (.*)[\r\n]+a\)[\s]+(.*)[\s]+b\)[\s]+(.*)[\s]+c\)[\s]+(.*) [\s]+d\)[\s]+(.*)[\s]+e\)[\s]+(.*)[\s]*/m';
$str = '1. A car averages 27 miles per gallon. If gas costs $4.04 per gallon, which of the following is closest to how much the gas would cost for this car to travel 2,727 typical miles?
a) $44.44 b) $109.08 c) $118.80
d) $408.04 e)
$444.40
2. When x = 3 and y = 5, by how much does the value of 3x2 – 2y exceed the value of 2x2 – 3y ?
a) 4
b) 14
c) 16
d) 20 e) 50';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
This question already has answers here:
Explode string by one or more spaces or tabs
(8 answers)
Closed 7 years ago.
I have unix disk output that I want to convert into an associated array for each line so a user can pick with available disks to use for the next vg creation.
Output of current array item. There is only 1 white space between each column I just did some tab's so it was easier to read.
array(11) {
[0]=> string(141) "vg1 LVM 136G /dev/cciss/c0d0p2 N/A N/A LOCAL N/A N/A NO "
[1]=> string(141) "vg2 LVM 1G /dev/mapper/mpath28p1 60060e80166fa70000016fa700000013 /dev/dm-33 R700 LS1000 0013 YES "
[2]=> string(141) "vg3 LVM 60G /dev/mapper/mpath27p1 60060e80166fa70000016fa700000012 /dev/dm-34 R700 LS1000 0012 YES "
[3]=> string(141) "vg4 LVM 60G /dev/mapper/mpath29p1 60060e80166fa70000016fa700000014 /dev/dm-35 R700 LS1000 0014 NO "
[4]=> string(141) "***AVAILABLE*** FREE 2G /dev/mapper/mpath21p1 60060e80167220000001722000000048 /dev/dm-37 R700 LS2000 0048 YES "
[5]=> string(141) "***AVAILABLE*** FREE 2G /dev/mapper/mpath22p1 60060e80167220000001722000000049 /dev/dm-36 R700 LS2000 0049 YES "
[6]=> string(141) "***AVAILABLE*** FREE 90G /dev/mapper/mpath23p1 60060e80166fa70000016fa70000000e /dev/dm-31 R700 LS1000 000e YES "
[7]=> string(141) "***AVAILABLE*** FREE 90G /dev/mapper/mpath24p1 60060e80166fa70000016fa70000000f /dev/dm-39 R700 LS1000 000f YES "
[8]=> string(141) "***AVAILABLE*** FREE 90G /dev/mapper/mpath25p1 60060e80166fa70000016fa700000010 /dev/dm-30 R700 LS1000 0010 YES "
[9]=> string(141) "***AVAILABLE*** FREE 90G /dev/mapper/mpath26p1 60060e80166fa70000016fa700000011 /dev/dm-32 R700 LS1000 0011 YES "
[10]=> string(141) "***AVAILABLE*** FREE 2G /dev/mapper/mpath30p1 60060e80167220000001722000000047 /dev/dm-38 R700 LS2000 0047 YES "
I want this to end up something like this. I've been trying different foreach loops but haven't got it to work yet. Any help/suggestions are appreciated.
[0] => name=>vg1 type=>LVM lun_size=>136G mpath_name=>/dev/cciss/c0d0p2 flun_id=>N/A dm_name=>N/A array_type=>LOCAL array_name=>N/A lun_id=>N/A shared=>NO
[1] => name=>vg2 type=>LVM lun_size=>1G mpath_name=>//dev/mapper/mpath28p1 flun_id=>60060e80166fa70000016fa700000013 dm_name=>/dev/dm-33 array_type=>R700 array_name=>LS1000 lun_id=>0013 shared=>NO
[2] => ....etc
Thanks
The solution is:
Loop through the original array elements
Use explode() function to split the string
Store elements in (key,value) pair in a temporary array
Push the temporary array at the appropriate position in the original array.
So your code should be like this:
// suppose $arr is your original array
$arrLength = count($arr);
for($i = 0; $i < $arrLength; ++$i){
$component_arr = explode(" ", $arr[$i]);
$tmp_arr = array();
$tmp_arr['name'] = $component_arr[0];
$tmp_arr['type'] = $component_arr[1];
$tmp_arr['lun_size'] = $component_arr[2];
$tmp_arr['mpath_name'] = $component_arr[3];
$tmp_arr['flun_id'] = $component_arr[4];
$tmp_arr['dm_name'] = $component_arr[5];
$tmp_arr['array_type'] = $component_arr[6];
$tmp_arr['array_name'] = $component_arr[7];
$tmp_arr['lun_id'] = $component_arr[8];
$tmp_arr['shared'] = $component_arr[9];
unset($arr[$i]);
$arr[$i] = $tmp_arr;
}
// display $arr array
var_dump($arr);
If they are tabs you should be able to use:
foreach($array as $row) {
$pieces = explode("\t",$row);
}
The sorting them out is the issue. The following gives me this. I'm not sure if I need to now use another foreach within there a combine of some sort. I'm been looking at examples but haven't found anything that has a string with that many fields.
foreach($disks as $row){
$arraynew = explode("\t", $row);
print_r($arraynew);
}
Array ( [0] => vg00 LVM 136G /dev/cciss/c0d0p2 N/A N/A LOCAL N/A N/A NO )
Array ( [0] => vg01 LVM 1G /dev/mapper/mpath28p1 60060e80013 /dev/dm-33 R700 LS4P991 0013 YES )
If it is accurate that the columns are only separated by 1 white space, I could suggest something along the lines of:
$result = Array();
foreach($main_array as $string){
$array = explode(" ", $string);
//now here you can sort them in the new array however you wish with the appropriate index and value.
}
Explode by space, " ", not tab, "\t"
Basically im trying to parse an stdClass object heres the code I use:
while($row = $data->fetch_assoc()){
try{
$products = $client->product_by_category_web_list($row['category_id'] , true, '', '2013-01-01', 0, 1500);
}catch(SoapFault $e){
echo "No Products under this Category";
}
$i = 0;
foreach($product as $products->item){
$cat_id = $row['category_id'];
$id = $product->$i->id;
$name = $product->$i->name;
$desc = $product->$i->descrShort;
$descLong = $product->$i->descrLong;
$avail = $product->$i->availableToSell;
$deliverable = $product->$i->deliverable;
$itemWeight = $product->$i->itemWeight;
$typelkp = $product->$i->typeLkp;
$stkbrandid = $product->$i->stkBrandId;
$dataVatId = $product->$i->dataVatId;
$query = "INSERT INTO `products` (`product_id` , `product_name` , `product_short_desc` , `product_long_desc` , `product_available , product_deliverable` , `product_item_weight` , `type_id` , `brand_id` , `vat_id`)
VALUES (? , ? , ? , ? , ? , ? , ? , ? , ? , ?)";
$stmt = $mysql->prepare($query);
$stmt->bind_param("isssiiiiii" , $id , $name , $desc , $descLong , $avail , $deliverable , $itemWeight , $typelkp , $stkbrandid , $dataVatId);
$stmt->execute();
$mctp = "INSERT INTO `products_categories` (`product_id` , `category_id` , `row_updated`)
VALUES (? , ? , ?)";
$match = $mysql->query($mctp);
$match->bind_param("iii" , $id , $cat_id , 0);
$match->execute();
$i++;
}
}
the Soap Call returns this:
object(stdClass)#1 (1) {
["item"]=>
array(2) {
[0]=>
object(stdClass)#3 (10) {
["id"]=>
int(79493)
["name"]=>
string(34) "Claud Butler Phobos Kids Bike 2014"
["descrShort"]=>
string(0) ""
["descrLong"]=>
string(1269) "
This year we have worked harder than ever to offer you a great range of quality junior bikes. All exclusively designed and tested in the UK with todays young riders and the popularity of cycling foremost in our minds.
A great bike is the key to a positive riding experience, enjoyment and reliability can be the largest factors when considering your new bike and with over 130 years of design and manufacturing experience we have become the brand of family cycling. Bikes have very much become a fashion item and we believe the kids choices are as important as Mum and Dads so we have a vast range of eye catching models to choose from. We also offer alloy and steel framed models to suit all budgets while maintaining great quality and performance at great value.
Frame: HiTen Steel
Fork: Rigid Steel
Headset: Steel with bearings
Bars: Steel
Stem: Steel Quill Type
Chainset: Steel
Front Brake: Alloy V Rear
Brake: Alloy V
Rims: Alloy
Front Hub: Steel
Rear Hub: Steel
Tyres: 20 x 1.95 Front, 20 x 1.95 Rear
Seatpost: Steel
"
["availableToSell"]=>
bool(true)
["deliverable"]=>
bool(true)
["itemWeight"]=>
float(20)
["typeLkp"]=>
int(1)
["stkBrandId"]=>
int(136)
["dataVatId"]=>
int(1)
}
[1]=>
object(stdClass)#4 (10) {
["id"]=>
int(64223)
["name"]=>
string(45) "DiamondBack Accomplice Black 20 Inch BMX 2012"
["descrShort"]=>
string(0) ""
["descrLong"]=>
string(1514) "
DiamondBack Accomplice Black 20 Inch BMX 2012 Introduction
If there were laws to prevent us from providing you with pro-level quality in a complete at a suspiciously low price, the new Accomplice would have us doing some hard time. Fortunately for both of us; there aren't. The bike has, however spent some time on the drawing board over the last year. In addition to being cleaned up and simplified, the Accomplice also bolsters a new frame with Affix Bush BB, Affix 9T cassette rear hub, Affix tyres and Butted tapered forks and bars! Built in Germany by the world famous KHE bmx experts.
Specification and Features of DiamondBack Accomplice Black 20 Inch BMX 2012
Diamondback Ambigram CRMO 3 piece crank on Affix Mid Bush BB (red ano) with Affix Orbis Alloy 25T sprocket
Rear U brake with soft compound pad and front caliper brake with alloy hinge levers
Front KHE Big "V" rim on Affix Ting Hub, rear Alienation Black Sheep rim on Affix 9T Hub with Affix 2.1 Tyres
Affix system stem with 2 piece butted handlebar 8" rise 28.8" width
KHE Exhib Project 2 saddle/post combo
Diamondback/KHE collaboration: Full 4130 Butted chromoly BMX frame with integrated head tube and Diamond "X" Brace, with full 4130 butted tapered chromoly BMX forks"
DiamondBack Accomplice Black 20 Inch BMX 2012 is perfect for:
Hitting the parks, jumps or a bit of street riding.
"
["availableToSell"]=>
bool(true)
["deliverable"]=>
bool(true)
["itemWeight"]=>
float(15)
["typeLkp"]=>
int(1)
["stkBrandId"]=>
int(215)
["dataVatId"]=>
int(1)
}
}
}
Whenever im using the foreach loop I get a error: Invalid Arguement supplied foreach. Im parsing it based on the answer ive just found:
Here
I want my search results to be in order of string position from smallest to greatest.
For example, searching for "banana" returns:
Babyfood, plums, bananas and rice, strained
Bananas, dehydrated, or banana powder
Bananas, raw
Bread, banana, prepared from recipe, made with margarine
CAMPBELL Soup Company, V8 SPLASH Juice Drinks, Strawberry Banana
CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana
CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana
I want "Bananas, raw" to come first because "banana" is the first word in the result, and I want "CAMPBELL Soup..." to come up last because "banana" is the last word.
I know I can use strpos() to find the position, but how do I put it all together?
You can do this easily in MySQL.
SELECT title,LOCATE('banana',title)
FROM myTable
WHERE LOCATE('banana',title) > 0
ORDER BY LOCATE('banana',title)
title represent column of MySql table.
It will involve a needlessly complex usort or something similar in PHP, best to do it in the query, for example:
SELECT data, INSTR(data, 'banana') as index
FROM table
WHERE data LIKE '%banana%'
ORDER BY index != 0, index
You could also select INSTR(titles, 'banana') as firstIndex and order by that value, ASC. This will return the index of the first located index of the needle within the haystack. Tag on a WHERE clause that omits anything that isn't LIKE '%banana%' and you should be set:
SELECT id, pubdate, title, INSTR(title, 'tea') as `index`
FROM article
WHERE title LIKE '%tea%'
ORDER BY `index` ASC;
If you don't get that data from an SQL query, you can sort that using usort and stripos ; something like this should do :
$arr = array(
"Babyfood, plums, bananas and rice, strained",
"Bananas, dehydrated, or banana powder",
"Bananas, raw",
"Bread, banana, prepared from recipe, made with margarine",
"CAMPBELL Soup Company, V8 SPLASH Juice Drinks, Strawberry Banana",
"CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana",
"CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana",
);
function compare_position($a, $b) {
return stripos($a, 'banana') - stripos($b, 'banana');
}
usort($arr, 'compare_position');
var_dump($arr);
i.e. you are here sorting with you own defined function, that compares the position (case-insentive) of "Banana" in the two strings it receives as parameters.
And you'll get this kind of output for your array, once sorted :
$ /usr/local/php-5.3/bin/php temp.php
array(7) {
[0]=>
string(37) "Bananas, dehydrated, or banana powder"
[1]=>
string(12) "Bananas, raw"
[2]=>
string(56) "Bread, banana, prepared from recipe, made with margarine"
[3]=>
string(43) "Babyfood, plums, bananas and rice, strained"
[4]=>
string(61) "CAMPBELL Soup Company, V8 SPLASH Smoothies, Strawberry Banana"
[5]=>
string(61) "CAMPBELL Soup Company, V8 V. FUSION Juices, Strawberry Banana"
[6]=>
string(64) "CAMPBELL Soup Company, V8 SPLASH Juice Drinks, Strawberry Banana"
}
Of course, if you get that data from an SQL query, it might be easier to do some additionnal calculations on the SQL side...
if you just want to emulate strpos:
select col, locate('banana', col) as pos from t
order by pos < 1, pos, length(col)