using variable on T_OBJECT_OPERATOR php - php

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

Related

Omitting Data From Array Output Based on Value

I am formatting data that is stored in two arrays using foreach loops and an If Statement. I am happy with my current output; however, I am having one issue. I don't want categories with No data or - TBD - as a data value to be displayed.
Here is my current PHP:
<?php
foreach ($finaltitle as $titlenumber => $titlename){
foreach ($techData as $tsnumber => $tsname){
if ($tsnumber == $titlenumber){
$finaltsdata = "<b>".$titlename." (".$tsnumber.") "."</b>: ".$tsname."<br>";
echo $finaltsdata;
}
}
}
?>
And its respective output:
Vehicle Name (1) : Audi S4
Body Style (2) : 5 Door Wagon
Drivetrain (6) : All-Wheel Drive
EPA Classification (7) : Small Station Wagon
Passenger Capacity (8) : 5
Passenger Volume (9) : 90.8
Base Curb Weight (10) : 4101
EPA Fuel Economy Est - City (26) : 14
EPA Fuel Economy Est - Hwy (27) : 21
Dead Weight Hitch - Max Trailer Wt. (31) : - TBD -
Dead Weight Hitch - Max Tongue Wt. (32) : - TBD -
Wt Distributing Hitch - Max Trailer Wt. (33) : - TBD -
Wt Distributing Hitch - Max Tongue Wt. (34) : - TBD -
Engine Order Code (40) :
Engine Type (41) : Gas V8
Displacement (42) : 4.2L/254
Fuel System (43) : SEFI
SAE Net Horsepower # RPM (48) : 340 # 6800
SAE Net Torque # RPM (49) : 302 # 3500
Trans Order Code (51) :
Trans Type (52) : 6
So in the case of this output I wouldn't want the following categories to be displayed because they either don't have a data value or their data value equals - TBD -.
Dead Weight Hitch - Max Trailer Wt. (31) : - TBD -
Dead Weight Hitch - Max Tongue Wt. (32) : - TBD -
Wt Distributing Hitch - Max Trailer Wt. (33) : - TBD -
Wt Distributing Hitch - Max Tongue Wt. (34) : - TBD -
Engine Order Code (40) :
Trans Order Code (51) :
Thanks so much for your help!
Skip unwanted items by continue statement
if ($tsnumber == $titlenumber){
if(empty($tsname) or $tsname === '- TBD -') continue;
$finaltsdata = "<b>".$titlename." (".$tsnumber.") "."</b>: ".$tsname."<br>";
echo $finaltsdata;
}

PHP: Custom parser for non-formatted text

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);

Convert PHP array string into array

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]);

PHP, Memory and Iteration

I've been noticing some odd behavior while experimenting with benchmarking SplFixedArrays. Take this little snippet of code, for instance...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable;
}
echo number_format( memory_get_usage() );
Which outputs...
1,032,080
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
1,032,384
Now, let's add a simple random integer onto the end while in the for loop...
<?php
$splFixedArray = new \SplFixedArray( 100000 );
echo number_format( memory_get_usage() ) . PHP_EOL;
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.';
var_dump( $variable );
for( $i = 0; $i < 100000; $i++ )
{
$splFixedArray[ $i ] = $variable . rand();
}
echo number_format( memory_get_usage() );
Which results in this...
1,034,320
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"...
129,834,272
What I'm curious about is why function calls are resulting in stacked memory usage. Is it normal that memory would not be freed up after the iteration?
This behavior is expected.
In the first case, you are storing the same value multiple times, which can be implemented as a single instance of the value and a batch of references to it, with a copy-on-write semantic for cases when the value at a given array index is changed.
In the second case, you are storing many different values, which can't be handled the same way; memory must be allocated for the full contents of each value, which results in the difference you see in memory consumption between the two cases.

Sort search results from MySQL by the position of the search query in the string using PHP

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)

Categories