Fill array with dynamic content in PHP - 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;

Related

Search Arrays to Multidimensional Array

I have 2 dimensional array like
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
result: array('Cancer Webinar','Company Anniversary');
The function call search from array list ($look) then find it to $events.
From the code above shoud return:
array('Cancer Webinar','Company Anniversary');
If the second array will just search by date use the following code
function search_from_array($array, $events) {
$result = [];
foreach($events as $event) {
if(in_array($event['date'], $array)) {
array_push($result, $event['desc']);
}
}
echo json_encode($result);
}
search_from_array($look, $events);
you can develop it more to can search with any key in the multidimensional array.
in case you want to search but many keys just add OR in the condition and make the same code for other keys like this
if(in_array($event['date'], $array) || in_array($event['desc'], $array))
You can make $look a dict, then check if the date key exist.
$events = array(
array(
'desc' => 'Cancer Webinar',
'date' => '20201219'
),
array(
'desc' => 'CSR Management',
'date' => '20200812'
),
array(
'desc' => 'Company Anniversary',
'date' => '20200309'
)
);
$look = array('20201219','20200309');
$look_dic = array_flip($look);
foreach($events as $event){
if(isset($look_dic[$event["date"]])){
$result[] = $event["desc"];
}
}
var_dump($result);

arrays passed in functions - 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.

Counting items in each category of a multidimensional array

I have a multidimensional array and I need to count how many items are in each category:
array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
)
I want to be able to split these up into categories.
For example;
Category 2 contains 2 items
Category 1 contains 1 item
Category 6 contains 1 item
Just to get the count of each category would be great, but to be able to re-arrange the array into categories would also be useful. I'd like to be able to do both.
I've tried searching StackOverflow but I couldn't find this specific query. I'm guessing this may use array_map somewhere but I'm not good with that function.
Any help is greatly appreciated!
If your array isn't too big a straightforward approach might be the easiest one. Create a new array, use categories as keys and iterate over your array, counting items.
I have written 3 functions that solves the criteria you have described. Keep in mind these functions are bare minimum and lack error handling. It is also assumed the $categories array which all the functions requires has the structure outlined in your question.
The first rearranges all items into the correct category.
function rearrangeCategories(array $categories) {
$calculated = [];
foreach($categories as $category) {
$calculated[$category['category']][] = $category['name'];
}
return $calculated;
}
The second creates an associative array of the amount of items in each category. The array index is the category name/id and the value is an integer declaring the amount of items.
function categoriesCount(array $categories) {
$calculated = [];
$arranged = rearrangeCategories($categories);
foreach($arranged as $category => $values) {
$calculated[$category] = count($values);
}
return $calculated;
}
The third function checks how many items are stored inside a specific category. If the category doesn't exists FALSE is returned. Otherwise an integer is returned.
function categoriesItemCount(array $categories, $key) {
$arranged = rearrangeCategories($categories);
if(!array_key_exists($key, $arranged)) {
return false;
}
return count($arranged[$key]);
}
I hope this helps, happy coding.
You can use something like this
$arr =
array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
);
$categoryCount = array();
$categoryList = array();
array_map(function($a) use (&$categoryCount, &$categoryList) {
$categoryId = $a['category'];
if (!isset($categoryCount[$categoryId])) {
$categoryCount[$categoryId] = 0;
}
$categoryCount[$categoryId]++;
if (!isset($categoryList[$categoryId])) {
$categoryList[$categoryId] = array();
}
$categoryList[$categoryId][] = $a['name'];
}, $arr);
print_r($categoryCount);
print_r($categoryList);
This will create 2 arrays: one with the counts and one with the elements rearranged
Try this way, i think it will fulfill your requirements.
$arr=array (
array(
'name' => 'Bob',
'category' => '2'
),
array(
'name' => 'Bill',
'category' => '6'
),
array(
'name' => 'John',
'category' => '1'
),
array(
'name' => 'Jack',
'category' => '2'
),
);
$result = call_user_func_array('array_merge_recursive', $arr);
//for just show array
print '<pre>';
print_r(array_count_values($result['category']));
print '</pre>';
//loop as you need
foreach(array_count_values($result['category']) as $k=>$v){
$item=($v>1)? 'items':'item';
echo "Category ".$k." Contains " .$v." ".$item."<br/>";
}

Know the element level in multidimensional array

Well, I am here again dealing with arrays in php. I need your hand to guide me in the right direction. Suppose the following array:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
The - (hyphen) symbol only illustrates the deep level.
Well, I need to build another array (or whatever), because it should be printed as an HTML select as below:
-fruits
--green
---limon
---mango
--red
---apple
-cars
--ferrari
---enzo
----blue
----black
---318
--lamborg
---spider
---gallardo
----gallado-96
-----blue
-----red
-----gallado-98
Looks that for each level element, it should add a space, or hyphen to determinate that it belongs to a particular parent.
EDIT
The have provide an answer provideng my final code. The html select element will display each level as string (repeating the "-" at the begging of the text instead multi-level elements.
Here's a simple recursive function to build a select dropdown given an array. Unfortunately I'm not able to test it, but let me know if it works. Usage would be as follows:
function generateDropdown($array, $level = 1)
{
if ($level == 1)
{
$menu = '<select>';
}
foreach ($array as $a)
{
if (is_array($a))
{
$menu .= generateDropdown($a, $level+1);
}
else
{
$menu .= '<option>'.str_pad('',$level,'-').$a.'</option>'."\n";
}
}
if ($level == 1)
{
$menu = '</select>';
}
return $menu;
}
OK, I got it with the help of #jmgardhn2.
The data
This is my array:
$temp = array(
array(
'name' => 'fruits',
'sons' => array(
array(
'name' => 'green',
'sons' => array(
array(
'name' => 'mango'
),
array(
'name' => 'banana',
)
)
)
)
),
array(
'name' => 'cars',
'sons' => array(
array(
'name' => 'italy',
'sons' => array(
array(
'name' => 'ferrari',
'sons' => array(
array(
'name' => 'red'
),
array(
'name' => 'black'
),
)
),
array(
'name' => 'fiat',
)
)
),
array(
'name' => 'germany',
'sons' => array(
array(
'name' => 'bmw',
)
)
),
)
)
);
Recursive function
Now, the following function will provide an array with items like [level] => [name]:
function createSelect($tree, $items, $level)
{
foreach ($tree as $key)
{
if (is_array($key))
{
$items = createSelect($key, $items, $level + 1);
}
else
{
$items[] = array('level' => $level, 'text' => $key);
}
}
return $items;
}
Calling the funcion
Now, call the function as below:
$items = createSelect($temp, array(), 0);
Output
If you iterate the final $items array it will look like:
1fruits
2green
3mango
3banana
1cars
2italy
3ferrari
4red
4black
3fiat
2germany
3bmw

Check if an array of an array contains a certain string

I'm checking to make sure an array of arrays does not contain certain strings before adding any new child arrays to the parent array
I want to make sure that if an array with the same website and condition exists a new child array will not be added to the parent array.
e.g. in this example the $newArr must not be inserted in to the array $arr because their already exists an array with the same website and condition.
$arr = array(
array(
'website' => 'amazon',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
),
array(
'website' => 'abe',
'price' => 20,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
);
$newArr = array(
'website' => 'amazon',
'price' => 60,
'location' => 'uk',
'link' => '...',
'condition' => 'new'
)
I'm looking for an easy solution as using the function in_array on the parent array is not enough.
code so far
$arr = array();
foreach($table->find('tr.result') as $row){
if(($website = $row->find('a img',0))
&& ($price = $row->find('span.results-price a',0))
&& ($location = $row->find('.results-explanatory-text-Logo'))
&& ($link = $row->find('a',0))){
$website = str_replace( array('.gif','.jpg','.png'), '', basename($website->src));
$price = floatval(trim(str_replace(',', '', $price->innertext), "£"));
$location = "uk";
$link = $link->href;
$arr[] = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
}
}
You loop over $arr each time to look for $website and $condition (always 'new'?) or you can keep a secondary array of the found keys. If you're starting with an empty $arr each time, the second approach will work and be faster.
$arr = array();
$keys = array();
foreach($table->find('tr.result') as $row){
if(...){
...
$condition = 'new'; // set as needed
// track seen keys
$key = $website . '|' . $condition; // assumes neither field contains '|'
if (!isset($keys[$key])) {
$keys[$key] = true;
$arr[] = array(...);
}
}
}
I hope the comments in the below code speak for themselves... I'm not a PHP pro, and this is probably not the most elegant way, but I believe the logic makes sense. Obviously the $new_array object has some variables that aren't declared but it's for example only.
I hope that helps and that no one down votes me :)
<?php
// Original array
$arr = array();
foreach($result as $row) {
// Get the new array as an object first so we can check whether to add to the loop
$new_array = array(
'website' => $website,
'price' => $price,
'location' => $location,
'link' => $link,
'condition' => 'new'
);
// If the original array is empty there's no point in looping through it
if(!empty($arr)) {
foreach($arr as $child) {
// Check through each item of the original array
foreach($new_array as $compare) {
// Compare each item in the new array against the original array
if(in_array($compare, $child)) {
// if there's a match, the new array will not get added
continue;
}
}
}
}
// If there's no match, the new array gets added
$arr[] = $new_array;
}
?>

Categories