arrays passed in functions - php - php

I have a question about the passing of multidimensionsal arrays in functions.
I have the following code (arrays), there are a few more arrays.
$product = array();
$product[] = array(
'Category' => "Smartphone",
'Seller' => "Apple",
'Product' => "<img src='Bild_iPhone_8.JPG' alt='iPhone 8' height='130px' />",
'Price' => 836,
'Selection' => "Mark1"
);
$product[] = array(
'Category' => "Smartphone",
'Seller' => "Samsung",
'Product' => "<img src='Bild_Galaxy_S8.JPG' alt='Galaxy S8' height='130px' />",
'Price' => 649,
'Selection' => "Mark2"
);
$product[] = array(
'Category' => "Notebook",
'Seller' => "Apple",
'Product' => "<img src='Bild_MacBookAir.JPG' alt='MacBook Air' width='130px' />",
'Price' => 999,
'Selection' => "Mark3"
);
I dont know now exactly how to put the parameters in a function.
I tried already a lot of possibilities, but nothin is working.
It should be possible to make requests with forms.
Can you please help me? Thanks a lot!
Greets, Mikra

I don't get your problem. You could pass the whole multi-dimensional array to a function the same way, you pass a one-dimensional array.
$products = [];
$products[] = [
'Category' => "Smartphone",
'Seller' => "Apple",
'Product' => "<img src='Bild_iPhone_8.JPG' alt='iPhone 8' height='130px' />",
'Price' => 836,
'Selection' => "Mark1"
];
// ... add more products
processProducts($products);
and later in your code
function processProducts($products) {
foreach ($products as $product) {
processProduct($product['Category'], $product['Seller'], and so on...);
// or..
processProduct($product);
}
}
function processProduct($category, $seller, ...) {
}
or
function processProduct($product) {
}

Use Array.push to insert multiple items to single array.
$product = array();
$item = array(
'Category' => "Smartphone",
'Seller' => "Apple",
'Product' => "<img src='Bild_iPhone_8.JPG' alt='iPhone 8' height='130px' />",
'Price' => 836,
'Selection' => "Mark1"
);
array_push($product,$item);
print_r($product);
and then you can pass the main $product array to any function.
calculatePrice($product);
To access first element use $product[0] or use foreach to loop over all.

Related

Fill array with dynamic content in PHP

I need to fill an array with a dynamic list of products.
To do so, I'm using the following code:
$list_array = array(
$products[] = array(
'SKU' => '0001',
'Title' => 'Bread',
'Quantity' => '',
),
$products[] = array(
'SKU' => '0002',
'Title' => 'Butter',
'Quantity' => '',
)
);
return $list_array;
It works fine if I know every product in the array.
But in my use case I have no idea which products are in the array.
So I want to fill the array with dynamic data.
I came up with something this:
$products = get_posts( 'numberposts=-1&post_status=publish&post_type=product' );
foreach ( $products as $product ) {
$products[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
),
}
return $products;
I know there is something really wrong with the array. But I couldn't figure out what it is.
The code you submitted cannot work. The short syntax $a[] = ... is to append data to the $a array, for example:
$a = [];
$a[] = 1;
$a[] = 2;
// $a = [1, 2]
You can also do it in a more efficient way with a map function:
function reduce($product)
{
return array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => '',
);
}
return array_map('reduce', $products);
It will execute the function reduce and replace value for each element of you array. Complete doc here: https://www.php.net/manual/en/function.array-map.php
Your problem is that you are overwriting the $products array that you are looping over inside the loop. Change the name of the variable in the loop to fix that:
$list_array = array();
foreach ( $products as $product ) {
$list_array[] = array(
'SKU' => $product->id,
'Title' => $product->post_title,
'Quantity' => ''
);
}
return $list_array;

How can I update value in the array by a condition on the php?

I have alt array like this :
$alt = array('chelsea', 'mu', 'arsenal');
I have photoList array like this :
$photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg',
'alt' => ''
),
array(
'id' => 2,
'name' => 'mu.jpg',
'alt' => ''
),
array(
'id' => 3,
'name' => 'arsenal.jpg',
'alt' => ''
)
);
I want to check a condition
If index plus 1 in the alt array same with id in the photoList array, it will update alt in the photoList array with value of alt array by index plus 1
I try like this :
foreach($photoList as $key1 => $value1) {
foreach ($alt as $key2 => $value2) {
if($value1['id'] == $key2+1)
$value1['alt'] = $value2;
}
}
Then I check with :
echo '<pre>';print_r($photoList);echo '</pre>';
The alt is still empty. It does not update
I hope the result like this :
photoList = array(
array(
'id' => 1,
'name' => 'chelsea.jpg',
'alt' => 'chelsea'
),
array(
'id' => 2,
'name' => 'mu.jpg',
'alt' => 'mu'
),
array(
'id' => 3,
'name' => 'arsenal.jpg',
'alt' => 'arsenal'
)
);
How can I do it?
You have to use the vars ($value1) by reference:
// THIS & is the trick
foreach($photoList as $key1 => &$value1) {
foreach ($alt as $key2 => $value2) {
if($value1['id'] == $key2+1)
$value1['alt'] = $value2;
}
}
Without that you work with an 'internal copy' of the sub-item $value1, so $photoList doesn't get updated.
A better approach will be to do that:
foreach($photoList as $key => $value)
$photoList[$key]['alt'] = $alt[$key];
This way round you use only one loop. Also, what's wrong with your original loop is that you are assigning the value to the temporary variable inside the loop. This is not affecting the array you are looping over.
EDIT:
I just figured out that you do not need to care about $photoList[$key]['id'] at all. It's irrelevant in this example as the order of the elements is the same in both arrays.

Last iteration values left in array

if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
when the foreach loop ends, only the last iteration value is left. I need all the values to be within the array.
Because order_detail will overwrite each time. Use array instead of simple variable.
$order_detail = array();
if ($cart = $this->cart->contents())
{
foreach ($cart as $item){
$order_detail[] = array(
'res_id' =>$this->session->userdata('menu_id[]'),
'customer_id' =>$coustomers,
'payment_id' =>$payment,
'name' => $item['name'],
'productid' => $item['id'],
'quantity' => $item['qty'],
'price' => $item['price'],
'subtotal' => $item['subtotal']
);
}
print_r($order_detail); exit;
Change this line
$order_detail = array(..);
to
$order_detail[] = array(..);
try this
first define the array
$order_detail=array();
array_push($order_detail, array(...));
array declaration must be outside the loop.

Add a new field to array elements in a foreach PHP - Laravel

I have this variable:
$families = array(
array(
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
And I want add to my $families items a field called 'href', like this:
$families = array(
array(
'href' => 'http://mipage/wall-art/AAER',
'expand' => '',
'family_id' => 'AAER',
'active' => true,
'description' => 'Wall Art',
'group_id' => 5
),
array(
'href' => 'http://mipage/personalised-mug/EEER',
'expand' => '',
'family_id' => 'EERR',
'active' => true,
'description' => 'Personalised Mugs',
'group_id' => 4
),
);
To do this I iterate $families in a foreach loop:
foreach($cat['families'] as $cat_fam) {
$cat['families'][]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
But this not works for me.
How can I make this?
You've to repalce empty [] with the specific key. For this update foreach block to get key of the element and use that inside foreach loop.
$cat['families'][$key] which points to individual element of the families array.
Like this,
foreach($cat['families'] as $key=>$cat_fam) {
$cat['families'][$key]['href'] = 'http//mysite/'.str_slug($cat_fam).'/'.$cat_fam['family_id'];
}
Demo: https://eval.in/636898
just iterate over the array, and add a key ahref
$newArray= array();
foreach($families as $innerArray){
$innerArray['ahref']='YOUR LINK HERE';
$newArray[] = $innerArray;
}
$families = $newArray ;//if you want to update families array
Do something like:
$href = array('href'=>'http://mipage/wall-art/AAER');
$combined_array = array_combine($families[0],$href);
Don't tested but you can try or modify as per your use
Please try this:
I think you also forgot to add index description in your str_slug call.
foreach($cat['families'] as &$cat_fam) {
$cat_fam['href'] = 'http://mysite/'.str_slug($cat_fam['description']).'/'.$cat_fam['family_id'];
}
You can use the php function array_walk
Liek this :
array_walk($cat['families'], function(&$family){
$family['href'] = 'http//mysite/'.str_slug($family).'/'.$family['family_id'];
});
note the $family variable is passed by reference.

PHP array_intersect / array_diff / combine array

$arr[] = array('title' => 'Overview');
$arr[] =array('title' => 'General');
$arr[] =array('title' => 'History');
$arr[] =array('title' => 'Construction');
$arr[] =array('title' => 'Plan');
$arr[] =array('title' => 'Other');
$info_arr[] = array("title" => "General", text => "value1");
$info_arr[] = array("title" => "History", text => "value1");
$info_arr[] = array("title" => "Construction", text => "value1");
$info_arr[] = array("title" => "Plan", text => "value1");
I need to be able merge these arrays together.So they look something like this. As I will need to loop thru the consolidated array. Other, Overview do not have any text values but still need to placed into the array.
$new_arr[] = array("title" => "General", text => "value1", "title" => "History", text => "value1", "title" => "Construction", text => "value1"
,"title" => "Plan", text => "value1","title" => "Overview", text => "","title" => "Other", text => "");
I have tried for loops (using count value), foreach loops, I thought array_intersect or array_diff don't see to solve the issue. This should not be so difficult, but I'm trying to piece together some really bad legacy code. Or the cube/florescent lights might have finally got to me.
Update:
while ($stmt->fetch()) {
$arr[] = array("title" => $Title);
}
and
while ($dstmt->fetch()) {
$info_arr[] = array("title" => $descriptionType, "descriptiontext" => $descriptionText); , "descriptiontext" => $val );
}
$dstmt & $stmt are queries.
I thought this would work but not so much
$r = array_intersect($arr, $info_arr);
var_dump($r);
Something like this Let me clarify:
$new_arr = array(array("title" => "General", text => "value1"),
array("title" => "History", text => "value1"),
array("title" => "Construction", text => "value1"),
array("title" => "Plan", text => "value1"),
array("title" => "Overview", text => ""),
array("title" => "Other", text => "")
);
If you want to work with these two arrays, you can just use the title as the key in $r.
foreach (array_merge($arr, $info_arr) as $x) {
$r[$x['title']]['title'] = $x['title'];
$r[$x['title']]['text'] = isset($x['text']) ? $x['text'] : '';
}
Or, you can go back a step and avoid having separate arrays by building the $r array in the same manner as you fetch your query results:
while ($stmt->fetch()) {
$r[$Title] = array('title' => $Title, 'text' => '');
}
while ($dstmt->fetch()) {
$r[$descriptionType] = array("title" => $descriptionType, "text" => $descriptionText);
}
Or, ideally, you could go back another step and avoid having separate queries by using a JOIN to get the same results in one query, but there's nothing in the question on which to base any specific suggestion for that.
As stated in the comments, the exact $new_arr you're requesting isn't possible. However, I think this will give you a similar result that should work for your purposes:
foreach ($info_arr as $infoArray) {
$found = array_search(array('title' => $infoArray['title']), $arr);
if (false !== false) {
unset($arr[$found]);
}
}
$new_arr = array_merge($info_arr, $arr);
It works by removing the "duplicates" from the original $arr before doing the array_merge().
If it's important to add an empty text value for the remaining items in $arr, do this before the array_merge():
foreach ($arr as &$arrArray) {
$arrArray['text'] = '';
}
The resulting array will look like this:
$new_arr[] = array(
array(
'title' => 'General',
'text' => 'value1',
),
array(
'title' => 'History',
'text' => 'value1',
),
array(
'title' => 'Construction',
'text' => 'value1',
),
array(
'title' => 'Plan',
'text' => 'value1',
),
array(
'title' => 'Overview',
'text' => '',
),
array(
'title' => 'Other',
'text' => '',
),
);

Categories