PHP: Keeps return as true - php

I cant figure out what i´m doing wrong. I keeps returning "På lager" in the if statement. But Shop 3, should return "Ikke på lager" in the foreach loop, where it calls the function.
<?php
$shopsArray = array(
"Shop1" => array (
"price" => 5,
"extUrl" => "https://tv2.dk/",
"logo" => "",
"stock" => "in stock",
"ean" => "5707400342642",
"shopName" => "Shop2",
),
"Shop2" => array (
"price" => 99,
"extUrl" => "https://cnn.com/",
"logo" => "https://eb.dk/",
"stock" => "in stock",
"ean" => "51010101010",
"shopName" => "Shop2.dk",
),
"Shop3" => array (
"price" => 50000000,
"extUrl" => "https://v2.dk/",
"logo" => "https://eb.dk/",
"stock" => "out of stock",
"ean" => "5707406556565655",
"shopName" => "Shop3",
)
);
foreach($shopsArray as $abc){
echo CheckStock();
}
function checkStock(){
global $shopsArray;
foreach ($shopsArray as $stockMgmt) {
if ($stockMgmt["stock"] == "in stock"){
return "På lager";
} else {
return "Ikke på lager";
}
}
}

You return from your checkStock() function as soon as $stockMgmt["stock"] == "in stock", and you do that three times. Try this code instead:
<?php
$shops = [
"Shop1" => [
"price" => 5,
"stock" => "in stock",
"ean" => "5707400342642",
"shopName" => "Shop2",
],
"Shop2" => [
"price" => 99,
"stock" => "in stock",
"ean" => "51010101010",
"shopName" => "Shop2.dk",
],
"Shop3" => [
"price" => 50000000,
"stock" => "out of stock",
"ean" => "5707406556565655",
"shopName" => "Shop3",
]
];
function checkStock($stockManagement)
{
return ($stockManagement["stock"] == "in stock") ? "På lager" : "Ikke på lager";
}
foreach ($shops as $shop => $stockManagement) {
echo $shop . ' = ' . CheckStock($stockManagement) . '<br>';
}
The function now uses the stock management array as an argument. In the function I use the Ternary Operator.
We only use one loop to walk through the main array of shops.
Note how I don't abbreviate unnecessarily. Variable names should clarify the meaning of the value, but not the type. So, not $shopsArray but just $shops or $shopsStock.
Now tested, thanks to medilies: PHP fiddle

Related

Refactor foreach with multilevel array

I'm currently returning results from a sql statement in an array like so:
$results = [];
foreach($promotionTool as $p){
$results[] = $p;
}
return $results;
Which my console shows in an object with this structure:
(2) [{…}, {…}]
0:
codeID: "41"
code: "123ABC"
rule_type: "Category"
attribute_type: "identifier"
attribute_title: "category number"
attribute_value: "234"
1:
codeID: "41"
code: "123ABC"
rule_type: "Category"
attribute_type: "amount"
attribute_title: "percent"
attribute_value: "25"
This is showing the data I expect but I'm a little bit lost on how to restructure this so that I can group on certain levels and finally return only an array of the attributes like so:
codeID
code
rule_type
array(
0:
attribute_type: "identifier"
attribute_title: "category number"
attribute_value: "234"
1:
attribute_type: "amount"
attribute_title: "percent"
attribute_value: "25"
)
How would I refactor my foreach to group at multiple levels in that way?
I guess this is what you are looking for:
<?php
$input = [
[
'codeID' => "41",
'code' => "123ABC",
'rule_type' => "Category",
'attribute_type' => "identifier",
'attribute_title' => "category number",
'attribute_value' => "234"
],
[
'codeID' => "41",
'code' => "123ABC",
'rule_type' => "Category",
'attribute_type' => "amount",
'attribute_title' => "percent",
'attribute_value' => "25"
]
];
$output = [];
array_walk($input, function ($e) use (&$output) {
$output[$e['codeID']][$e['code']][$e['rule_type']][] = [
'attribute_type' => $e['attribute_type'],
'attribute_title' => $e['attribute_title'],
'attribute_value' => $e['attribute_value']
];
});
print_r($output);
This could be a variant easier to read:
array_walk($input, function ($e) use (&$output) {
$codeID = &$e['codeID'];
$code = &$e['code'];
$rule_type = &$e['rule_type'];
$output[$codeID][$code][$rule_type][] = [
'attribute_type' => $e['attribute_type'],
'attribute_title' => $e['attribute_title'],
'attribute_value' => $e['attribute_value']
];
});
The output obviously is:
Array
(
[41] => Array
(
[123ABC] => Array
(
[Category] => Array
(
[0] => Array
(
[attribute_type] => identifier
[attribute_title] => category number
[attribute_value] => 234
)
[1] => Array
(
[attribute_type] => amount
[attribute_title] => percent
[attribute_value] => 25
)
)
)
)
)

Return result of recursive function

I got a recursive function which currently echo the results. I want this function to return results and loop them with foreach inside markup.
I understand that i should use some kind of iteration for each array to get my desired result but have failed with that. Currently my code look like this(with attempts to iterate):
public static function recursiveChildCategory($categories = array(), $depth = 0, $i = 0) {
$ca = [];
// Loop through categories
foreach($categories as $key => $category){
echo str_repeat(" ", $depth);
echo "<a href='".implode('/', $category['breadcrumb'])."'>{$category['title']}</a>";
echo '<br>';
$ca[$i] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
self::recursiveChildCategory($category['child'], $depth + 1, $i++);
}
}
return $ca;
}
And incoming array to the function:
Array (
[0] => Array (
[id] => 7
[title] => Deserts
[slug] => deserts
[child] => Array (
[0] => Array (
[id] => 8
[title] => Space
[slug] => space
[child] => Array (
[0] => Array (
[id] =>
[title] =>
[slug] =>
[child] => Array ( )
)
)
)
)
)
)
Currently it just returns first level of child categories "Deserts", but nothing about "Space".
As desired result i want function to return all categories with $depth and infinite path to multiple child categoires (to do the same work as currently echo doing).
Thanks in advice
Try this and tell me if it's what you are looking for :
The array for my test :
$array = [
0 => [
"id" => 7,
"title" => "Deserts",
"slug" => "deserts",
"child" => [
0 => [
"id" => 8,
"title" => "Space",
"slug" => "space",
"child" => [
0 => [
"id" => 9,
"title" => "Test",
"slug" => "test"
]
]
]
]
]
];
The recursive function :
function recursiveChildCategory($categories, $depth = 0, $ca = []) {
// Loop through categories
foreach($categories as $key => $category){
$ca[$depth] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
$ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
} else {
break;
}
}
return $ca;
}
Now, how to use it :
$test = recursiveChildCategory($array);
var_dump($test);
And this is the output :
array(3) {
[0]=>
array(2) {
["id"]=>
int(7)
["title"]=>
string(7) "Deserts"
}
[1]=>
array(2) {
["id"]=>
int(8)
["title"]=>
string(5) "Space"
}
[2]=>
array(2) {
["id"]=>
int(9)
["title"]=>
string(4) "Test"
}
}
Here is a link to test it : http://sandbox.onlinephpfunctions.com/
EDIT : I made some modification because in OP example array can have multiple result in first "depth", here is the "new" solution :
The array for test :
$array = [
"0" =>
[ "id" => 3, "title" => "Subcat", "slug" => "subcat", "child" =>
[ "0" =>
[ "id" => 5, "title" => "Subsubcat2", "slug" => "subcat2", "child" =>
[ "0" =>
[ "id" => "", "title" => "", "slug" =>"", "breadcrumb" => [ "0" => "homeworld", "1" => "cat", "2" => "subcat", "3" => "subcat2" ], "child" => [ ] ]
]
]
]
],
"1" =>
[ "id" => 4, "title" => "Kalahari", "slug" => "kalahari", "child" =>
[ "0" => [ "id" => 7, "title" => "deserts", "slug" => "deserts", "child" =>
[ "0" =>
[ "id" => 8, "title" => "Ural", "slug" => "ural", "child" =>
[ "0" => [ "id" =>"", "title" =>"", "slug" =>"", "child" => [ ] ] ]
]
]
]
]
]
];
The function : I just add $ca[$depth][] instead of $ca[$depth]
function recursiveChildCategory($categories, $depth = 0, $ca = []) {
// Loop through categories
foreach($categories as $key => $category){
$ca[$depth][] = [
'id' => $category['id'],
'title' => $category['title'],
];
if(isset($category['child'])) {
// Loop
$ca = recursiveChildCategory($category['child'], $depth + 1, $ca);
} else {
break;
}
}
return $ca;
}
And now the result :
$test = recursiveChildCategory($array);
foreach ($test as $depth => $c) {
echo "depth : ".$depth."\n";
foreach ($c as $result) {
echo "Title : ".$result['title']."\n";
}
echo "=============\n";
}
The output is :
depth : 0
Title : Subcat
Title : Kalahari
=============
depth : 1
Title : Subsubcat2
Title : deserts
=============
depth : 2
Title :
Title : Ural
=============
depth : 3
Title :
=============
Test here : link

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Multiply price and quantity of each row, then sum to calculate total

My code goes as:
<?php
$items = array(
array("SKU" => "a49w8dsa", "Title" => "Socks", "Description" => "Sports socks", "Price" => "1.50", "Quantity" => "4"),
array("SKU" => "ta8dla", "Title" => "T-shirt", "Description" => "ABC Brand undershirt", "Price" => "14.25", "Quantity" => "2"),
array("SKU" => "yusa982", "Title" => "Flip Flips", "Description" => "XYZ Brand Beach Flops", "Price" => "2.88", "Quantity" => "5"),
array("SKU" => "gnbaiue", "Title" => "Ball Cap", "Description" => "No Name", "Price" => "3.58", "Quantity" => "1"),
array("SKU" => "ythwq836", "Title" => "Frizbee", "Description" => "Whammo Frisbee Disc", "Price" => "2.47", "Quantity" => "2")
);
$final = array_shift($items);
foreach (array_column as $key => &$value){
$value += array_sum(array_row($Price . $Quantity));
}
unset($value);
var_dump($final);
I want to grab the price of each item, multiply it by the quantity in that array and add the sums to a variable, then print.
Get price of each item into an array, then finally sum it up using array_sum() -
$eachPrice = array();
foreach ($items as $key => $val) {
$eachPrice[] = $val['Price'] * $val['Quantity'];
}
$totalPrice = array_sum($eachPrice);
var_dump($totalPrice); // should be total price of all items

Using foreach and nested array to insert rows in MySql with PHP

I've written the follow code to try and insert data into a table on the database. However it's just inserting letters. I'm not sure what I'm doing wrong.
$media_items = array(
array (
"media_name" => "Facebook",
"link_url" => "http://www.facebook.com/insightdezign",
"icon" => "facebook.png",
"size" => "48",
"order" => "0"
),
array (
"media_name" => "Twitter",
"link_url" => "http://www.twitter.com/insightdezign",
"icon" => "twitter.png",
"size" => "48",
"order" => "1"
)
);
foreach ($media_items as $media_item) {
if (is_array($media_item)){
foreach ($media_item as $item) {
$rows_affected = $wpdb->insert( $ffui_items, array( 'media_name' => $item['media_name'], 'link_url' => $item['link_url'], 'icon' => $item['icon'], 'size' => $item['size'], 'order' => $item['order'] ) );
}
}
}
Inside your nested foreach loop, you will be looping over strings, not arrays. As a result of type juggling, the indexes will be evaluated to 0. Since PHP also accepts $foo['bar'] syntax on strings, it will just return the first letter.
You can simply remove the nested foreach loop and do it as follows:
foreach ($media_items as $media_item)
{
if (is_array($media_item))
{
$rows_affected = $wpdb->insert( $ffui_items,
array(
'media_name' => $media_item['media_name'],
'link_url' => $media_item['link_url'],
'icon' => $media_item['icon'],
'size' => $media_item['size'],
'order' => $media_item['order']
) ;
}
}

Categories