take out components from array session and save in Database LARAVEL 9 - php

How are you? Hope well. I have e-commerce project on laravel 9. Actually i want to make checkout. I have add to cart function with sessions(it works fine), i want to make checkout. I am recieving cart with sessions
$order = session('cart');
var_dump($order);
This is working fine. It makes output with array('title','price','quantity'). Actually i want to put out each other and next save it in database.
array(1) { [52]=> array(3) { ["title"]=> string(11) "MacBook Pro" ["quantity"]=> int(1)
["price"]=> string(7) "2399.99" } }
This is array, which i have in checkout page. Please help me. I want to put out each other, for example: $order_title = ....
$order_price = ...
$order_quantity = ...
and next save it in database, table named 'orders'.

Just insert / add the data how you do normally.
$carts = session('cart');
foreach($carts as $cart)
{
Order::create([
'order_title' => $cart['title'],
'order_quantity' => $cart['quantity'],
'order_price' => $cart['price'],
]);
}

first read data from session then iterate through elements of array and save them:
$carts = session('cart');
foreach($carts as $cart) {
$order = new Order();
$order->order_title = $cart['title'];
$order->order_quantity = $cart['quantity'];
$order->order_price = $cart['price'];
$order->save();
}

Related

PHP and Pods: Combine array values only into new array

Long time user, first time poster. The forums here have got me out of a lot of trouble but I'm really stuck on this one.
I'm using Pods for a Custom Post Type that has a Custom Field where a user can enter a numeric value. eg. or 4 or 2 etc
I want to display the total sum of this Custom Field across all user made posts on the front end. To achieve this I'm using a Pods Template to make a short code for the front end, but to do the calculation I'm using PHP.
So my current PHP is:
function jobs_total ($id) {
$pods = pods ('pledged_job', $id);
$jobs = ($pods->field ('jobs_pledged'));
$a = ($jobs);
$b = explode(' ', $a);
var_dump($b);
}
And the result I get so far is:
array(1) { [0]=> string(1) "5" }
array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "7" }
How do I take the numeric values from "_", which are correctly appearing from post entries, and combine them in a new array so I can perform an 'array_sum' and return the total of those numbers?!
I'm a PHP novice so I'm not sure if this is obvious or if it's a clash between Pods terms and standard PHP.
Thanks in advance!!
Final code wrapped in shortcode to allow for displaying on the frontend through Elementor
function jobs_shortcode () {
$jobs = get_posts(array(
'post_type' => 'pledged_job',
'post_status' => 'publish',
'numberposts' => -1, ));
$total = 0;
foreach ($jobs as $field) {
$total += (int) get_post_meta($field->ID, 'jobs_pledged', true);
}
echo $total;
}
add_shortcode( 'jobs', 'jobs_shortcode' );

Why is it when I take 3 array values it shows error but when I only show 1 value it works?

When I use var_dump($paid) it will show all the values
this is the code. If I use all 3 description, amount, and payment_type it will show an error that the amount is undefined. But if I use only 1 like for example I use only the description and erase the rest the code will work
$paid = array();
foreach ( $user as $u ) :
$paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
if ($paidDetail->count()) :
$paid[]['description'] = $paidDetail[0]->description;
$paid[]['amount'] = $paidDetail[0]->amount;
$paid[]['payment_type'] = $paidDetail[0]->payment_type;
endif;
endforeach;
return $paid;
this is for the view/blade to show the details in the frontend
{{ $paid['description'] }}
{{ $paid['amount'] }}
{{ $paid['payment_type'] }}
showing each 1 of them works but showing all of them at the same time will show an error saying that the 2nd value is undefined
Below is the var_dump($paid)
array(1) { ["description"]=> string(33) "Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(350) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }
array(1) { ["description"]=> string(38) "Test Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(351) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }
It's just because,
Your foreach loop overwriting 0 Index Parameters and every time last record stores in Array.
And Executing query in every iteration of foreach loop may reduce your code performance.
You Should use laravel eloquent model and relationship for this issue.
https://laravel.com/docs/5.5/eloquent-relationships
Try this:
$paid = array();
$i=0;
foreach ( $user as $u ) :
$paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
if ($paidDetail->count()) :
$paid[$i]['description'] = $paidDetail[0]->description;
$paid[$i]['amount'] = $paidDetail[0]->amount;
$paid[$i]['payment_type'] = $paidDetail[0]->payment_type;
$i++;
endif;
endforeach;
return $paid;
The main issue with you code is that you forgot to use a index on you array. Adding $i as an index makes sure that each user payment have his own index.
Note
Lopping thru an collection and doing a SQL QUERY for each user is not wrong but also not a good practice. Try to get both in one SQL Statment.

Understanding CodeIgniter objects and multidimensional arrays

I'm working on a project in CodeIgniter 2 and now I'm stuck on the most basic of concepts.
Model:
Get an object array from my table which contains all rows that match a specific value for a field named foo. There can be one or more rows that match. In this example, two rows.
public function get_sample($foo)
{
$query = $this->db->get_where('sample_db', array('foo' => $foo));
return $query->result();
}
Controller:
Assign the results and make output available to view.
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
$this->load->view('view', $data);
}
View:
echo var_dump($array); // for testing
echo $array[1]->text
var_dump() of $array:
array(2) {
[0]=> object(stdClass)#23 (4) {
["id"]=> string(1) "1"
["foo"]=> string(3) "bar"
["number"]=> string(4) "1234"
["text"]=> string(23) "This is content in 1234"
}
[1]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
The rendered ouput of echo $array[1]->text; is: This is content in 9999
And I understand how all that is working: $array[1]->text is the content of the text field in the array object with the index of 1, my second object.
However, I have a field called number and I want to access the object with a certain number and get its corresponding text value.
Example: How can I retrieve the value of text where the number is 9999? I cannot use $array[1]->text since I can never be sure of the object's position in the array. Something like $array['number' => '9999']->text, but I know that's not right. Maybe I need to loop through the array looking for a match?
This looks so simple yet everything I've tried has failed and resulted in various PHP errors. I've been studying the PHP manual here and here, but cannot seem to find anything about what I'm looking to do, or maybe I'm just misapplying what I'm reading. Any guidance is appreciated.
In addition to an answer using best practices following the MVC model, I'm hoping for a link to the proper page in the documentation, as well as pointing out any errors in my wording/terminology above.
EDIT:
This answer contains the actual code I used to solve my problem. Although, Yagi's answer was accepted because it put me in the right direction.
How about using this :
foreach ($array as $row) {
if ($row->number == '9999') {
echo $row->text;
}
}
Loop through the array, and find the number object value of 9999 and get the text
Why don't you just to a query and search for that number (or order by that number?)
Either way, what you need is a multidimensional array search function (that iterates through array of object and returns the found field value combo )
Something like this (put this in helper)
function multi_array_search($array, $field, $value)
{
$results = array();
if (is_array($array))
{
if ($array->$field == $value) //chek the filed against teh value, you can do addional check s(i.e. if field has been set)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, multi_array_search($subarray, $key, $value)); //recurisve serach
}
return $results;
}
//than in view or in controller, depending where you need it
$result = multi_array_search($array, "number", "9999");
var_dump($result) will return or whether number of foudn instances
array() {
[0]=> object(stdClass)#24 (4) {
["id"]=> string(1) "2"
["foo"]=> string(3) "bar"
["number"]=> string(4) "9999"
["text"]=> string(23) "This is content in 9999"
}
}
you might be looking for something like this...
array_filter($array, function($o){ return $o->number == 9999; } );
http://php.net/manual/en/function.array-filter.php
EDIT
$o is the parameter in the callback function. each element of the array is passed to the callback function. if the function returns false, the element will be filtered out.
$arr = array(
(object) array(
'num' => 33,
'text' => 'hello',
),
(object) array(
'num' => 44,
'text' => 'world',
),
);
$filtered = array_filter($arr, function($o){ return $o->num == 33; });
echo $filtered[0]->text; // hello
as you stated, index will remain, so use array_values or array_shift. here's an example with function
function get_by_num($arr, $num){
return array_shift(array_filter($arr, function($o) use ($num) { return $o->num == $num; }));
}
$obj = get_by_num($arr, 44);
var_dump($obj);
// object(stdClass)#2 (2) { ["num"]=> int(44) ["text"]=> string(5) "world" }
in this case $obj will be either NULL if element is not found, or the first match. $num is transferred along so you can use any value. you can even improve it:
function get_first_match($arr, $field, $val){
return array_shift(array_filter($arr, function($o) use ($field, $val) { return $o->{$field} == $val; }));
}
$obj = get_first_match($arr, 'num', 44);
and now you can search any field. in your case
$obj = get_first_match($array, 'number', 9999);
Thanks to Yagi's answer, I came up with the following very simple solution. I loop through the array and assign the value of text to a new array with an index that matches the value of number. Then in the view file, I can access the text value based on this index.
Controller:
public function view($foo)
{
$data['array'] = $this->sample_model->get_sample($foo);
foreach ($data['array'] as $row) {
$data['result'][$row->number] = $row->text;
};
$this->load->view('view', $data);
}
View:
if (isset($result[9999])) echo $result[9999];

How do I load a Magento product and find stores it's assigned to

I've been asked to reverse engineer some orders (from an Ebay Extension) and find out which store they really used.
To flesh out an example; we run several stores from one Magento backend selling various products. These are all sold on eBay using a single merchant account.
So what I need to do is load the order as it stands assigned against the eBay store, load the items attached to that order and then see what other stores that item is used on.
Once I get that far I can simply filter out the admin storeID and the eBay storeID which will leave with the store I'm looking for.
this is what I have so far:
foreach($collection->getItems() as $order):
// need to do this to load correct order information
$order = Mage::getModel('sales/order')->loadByIncrementID($order->getIncrementId());
$items = $order->getItemsCollection();
foreach($items as $item) {
// need to do this to get the actual item, not the item on the order
$item = Mage::getModel('catalog/product')->load($item->getItemId());
// do something to get the other store ids
}
endforeach;
You can use Mage_Catalog_Model_Product::getStoreIds() method to get list of these stores:
$item = Mage::getModel('catalog/product')->load($item->getItemId());
$storeIds = $item->getStoreIds();
Then $storeIds will contain array of store ids, and when you dump that:
var_dump($storeIds)
you should get following result:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "3"
[2]=>
string(1) "5"
}
try this
$item = Mage::getModel('catalog/product')->load($item->getItemId());
$storeId = $item->getStoreId();
this works just fine for me.

Multiple items in a PHP shopping cart

I'm in the progress of making a shopping cart in PHP. To check if a user has selected multiple products, I put everything in an array ($contents). When I output it, I get something like "14,14,14,11,10". I'd like to have something like "3 x 14, 1 x 11, 1 x 10". What is the easiest way to do that? I really have no clue how to do it.
This is the most important part of my code.
$_SESSION["cart"] = $cart;
if ( $cart ) {
$items = explode(',', $cart);
$contents = array();
$i = 0;
foreach ( $items as $item ) {
$contents[$item] = (isset($contents[$item])) ? $contents[$item] + 1 : 1;
$i++;
}
$smarty->assign("amount",$i);
echo '<pre>';
print_r($contents);
echo '</pre>';
Thanks in advance.
Why not build a more robust cart implementation?
Consider starting with a data-structure like this:
$cart = array(
'lines'=>array(
array('product_id'=>14,'qty'=>2),
array('product_id'=>25,'qty'=>1)
)
);
Or similar.
Then you could create a set of functions that operate on the cart structure:
function addToCart($cart, $product_id, $qty){
foreach($cart['lines'] as $line){
if ($line['product_id'] === $product_id){
$line['qty'] += $qty;
return;
}
}
$cart['lines'][] = array('product_id'=>product_id, 'qty'=>$qty);
return;
}
Of course, you could (and perhaps should) go further and combine this data structure and functions into a set of classes. Shopping carts are a great place to start thining in an object-oriented way.
The built-in array_count_values function might does the job.
E.g:
<?php
$items = array(14,14,14,11,10);
var_dump(array_count_values($items));
?>
Outputs:
array(3) {
[14]=>
int(3)
[11]=>
int(1)
[10]=>
int(1)
}
You would benefit from using a multi dimensional array to store your data in a more robust structure.
For example:
$_SESSION['cart'] = array(
'lines'=>array(
array('product_id'=>14,'quantity'=>2, 'item_name'=>'Denim Jeans'),
...
)
);
Then to add new items to the cart you can simply do this:
$_SESSION['cart'][] = array('product_id'=45,'quantity'=>1, 'item_name'=>'Jumper');
When you let a user add an item you need to add it in the right position in the array. If the product id already exist in the array, you need to update it. Also always be careful of users trying to enter zero or minus numbers!

Categories