Php array exclude array

How to remove empty array from multidimensional array?

In you code, you wrongly used the array_filter, you can check its menual.

array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )

ei@localhost:~$ php test.php array(4) < [0]=>array(1) < [0]=>string(42) "Last Updated: Thu Apr 21 17:03:23 2016 PST" > [1]=> array(0) < >[2]=> array(0) < >[3]=> array(1) < [0]=>string(15) "MODEL: MODEL_NC" > > array(2) < [0]=>array(1) < [0]=>string(42) "Last Updated: Thu Apr 21 17:03:23 2016 PST" > [3]=> array(1) < [0]=>string(15) "MODEL: MODEL_NC" > > 

Your current array values are following:

$exclude1 = array( array("Last Updated: Thu Apr 21 17:03:23 2016 PST"), array(""), array(""), array("MODEL: MODEL_NC"), ); 

See the output of current array. it’s look like the follwoing :

Output will be:

Array ( [0] => Array ( [0] => Last Updated: Thu Apr 21 17:03:23 2016 PST ) [1] => Array ( [0] => ) [2] => Array ( [0] => ) [3] => Array ( [0] => MODEL: MODEL_NC ) ) 

Use array_filter and array_map

$newArray = array_filter(array_map('array_filter', $exclude1)); 

Check the final output:

Array ( [0] => Array ( [0] => Last Updated: Thu Apr 21 17:03:23 2016 PST ) [3] => Array ( [0] => MODEL: MODEL_NC ) 

So it will remove empty array from your previous multidimensional array.

function array_remove_null($array) < foreach ($array as $key =>$value) < if(is_null($value)) unset($array[$key]); if(is_array($value)) $array[$key] = array_remove_null($value); >return $array; > 
$arr = array_filter_recursive($arr); $arr = array_filter($arr); 

Источник

Filtering Arrays in PHP

As a result, most developers will use [cci]for[/cci] loops to manually iterate over arrays. It works, but consumes several lines of code and generally looks ugly.

There are a handful of functions built into PHP that can be lifesavers when building a project.

Mapping Arrays

The most widely recognized PHP array method is [cci]array_map()[/cci]. With this method, you can «map» an arbitrary function to every element in an array.

Let’s say, for example, an API or database lookup gives you an array of numbers but for some reason all of these numbers are stored as strings. It would be far better if we could apply, say WordPress’ [cci]absint()[/cci] function to each item before using it elsewhere in our code.

// Get an array of strings from a data source
$our_array = get_some_data_from_somewhere();

// Turn those strings into integers
$our_array = array_map( ‘absint’, $our_array );

Filtering Arrays

Sometimes, an array contains a lot more data than we actually need to use. Perhaps its a collection of all WordPress posts and we want to specifically exclude certain posts that have been printed elsewhere on the page.[ref]In some cases, you might just run a second query. With a [cci]post__not_in[/cci] parameter, but then you’re running two queries. The second version is also not cachable.[/ref]

Luckily, the [cci]array_filter()[/cci] method allows us to iterate through our array and determine whether or not individual elements should remain in the collection:

// Get an array of strings from a data source
$our_array = get_some_data_from_somewhere();

// We want to exclude posts from the following array
$exclude = array( 15, 27, 123 );

// Now do the filter, using a closure
$filtered = array_filter( $our_array, function( $item ) use ( $exclude ) if ( in_array( $item->ID, $exclude ) ) return false;
>

When the closure returns true, the current item will remain in the array. When it returns false, the item is skipped. You could just filter the array back to itself — storing the result of [cci]array_filter()[/cci] in a second variable allows us to be nondestructive in our operation (if we need the original array again for any reason).

Reducing Arrays

My personal favorite, though, is [cci]array_reduce()[/cci]. Like [cci]array_filter()[/cci] above, it can be used to filter an array down to a specific subset. Since it builds up an internal array (the reduce function applies iteratively to the carrying array), you can also manipulate the keys of the array at the same time.

For example, let’s say you’re working again with an array of posts in WordPress. You want to strip out 2 posts that have already been used on the page. At the same time, you want to convert your numerically-indexed array to an associative array keyed by post IDs.

// Get an array of strings from a data source
$our_array = get_some_data_from_somewhere();

// We want to exclude posts from the following array
$exclude = array( 15, 27, 123 );

// Now reduce the array, using a closure
$reduced = array_reduce( $our_array, function( $carry, $item ) use ( $exclude ) if ( ! in_array( $item->ID, $exclude ) ) $carry[ $post->ID ] = $item;
>

You’re effectively using [cci]array_reduce()[/cci] to filter the array, but killing two birds with one stone by rekeying the array at the same time.

What other PHP array functions do you use?

Источник

How to exclude data from an array?

On a product page I want to show 4 other products selected randomly, but never the product that is already being displayed. The product id of the displayed one is $_product->getId() and all the products go into a $result[] array like this:

foreach($collection as $product)< $result[]=$product->getId(); > 

I’m using $need = array_rand($result, 4); to get the ids of the 4 random products, but it might include the id of the product on display. How do I exclude $_product->getId() from the $need[] array? Thank you.

4 Answers 4

Don’t put id of the product you don’t want to show into $result :

$currentProductId = $_product->getId(); foreach ($collection as $product) < if ($product->getId() != $currentProductId) $result[] = $product->getId(); > 

Is it acceptable to just not put the current product ID in the array?

foreach($collection as $product) < if( $product != $_product) $result[] = $product->getId(); > 

You might generate your random numbers first, like so:

$rands = array(); while ($monkey == false)< $banana = rand(0,4); if (in_array($banana, $rands) && $banana != $_product->getId()) < $rands[] = $banana; >if (sizeOf($rands) == 4) < $monkey = true; >> 

Then you could pipe them through your product grabber. Obviously, you’d need to figure out the bounds for rand yourself but you know more about your app than I do. Picking your numbers first is much cheaper computationally than pulling records and THEN checking to make sure that they’re unique.

Of course, if this is database-backed, you could solve it much more elegantly by writing a new query.

Источник

How to exclude an item in an array in PHP

I have created a little php file that will display a list of products that «Customers have also bought» that I want to display on each of my products pages. However, I want to exclude the same product showing up as an «also bought» on the product page. Here is the php file I have created that loads a random product on page load:

THIS FILE IS CALLED "**products.php**" gallery-image 
Product 1
'; $product2 = ' gallery-image
Product 2
'; $product3 = ' gallery-image
Product 3
'; $product4 = ' gallery-image
Product 4
'; $product5 = ' gallery-image
Product 5
'; $products = array($product1, $product2, $product3, $product4, $product5); shuffle($products); ?>
This file is called **product1.php** 

Customers Also Bought

It would be helpful if we knew the structure of the data of the current product. Is it stored in another array? A variable?

No, it is stored just like it written above and then I am just echoing/printing in a separate php file.

So on each product page you would like to output both the main product and then an array of additional products, but right now I only see you outputting $products[0] to the page. Is there code which you aren’t including?

The code above shuffles each of the products so that one of them appears on page load . in a random order. I want to exclude from the random order the product that is already being shown

5 Answers 5

Use unset() to remove an item in a array. But you have to provide a key and the value to the array.

Hello and welcome to Stack Overflow! You might want to take a quick look at the site’s markdown guide. It will help you post easier to read answers.

Try in_array() or array_key_exists();

$products= [1,2,3,4,5]; $array=[1,5]; foreach($products as $key => $product) < if (array_key_exists($key,$array))< unset($products[$key]); >> 

this should do the trick, // loop through the new array to create your html

$array = array("a","b","c","d","e"); $array2 = array("d","b"); shuffle($array); for($i=0;$i > echo $array[0]; 

You should have the current product stored somewhere, so you just need to compare that value with the values in your $products array. You can use in_array to find the $current_product in the $products array. Something like the below:

$current_product = '1'; $products = array('1', '2', '3', '4'); if (in_array($current_product, $products))

You can use unset() to remove the value from the array, but be sure to supply the array key or index value when you do so.

After a conversation with the OP:

I think you need to restructure your code. If you can restructure the HTML in products.php, then store all of your products, including the main product, in php variables. Then, print out the main product and additional products to the page with php variables. Something like:

That way all of your data is stored in PHP variables. If it is all stored in variables then you can use PHP to compare the two products with the method above.

HOWEVER, if you can’t change products.php then you are going to need to parse through the HTML and find some identifying information that will indicate which product is being shown. After you identify the product, you will then need to compare it with the HTML which you stored in $products to find a match. Basically, you need to compare one string against another, and you really don’t want to have to go down that route.

Ok, after reading and trying to implement all of the offered suggestions without success I came up with a solution that will work for me. I realize that this is a more crude way of doing it but it is the only way I could achieve what I needed.

I modified the php file that contained all of the product names and html to be echoed on the main product pages.

$all_products = array($product1, $product2, $product3, $product4, $product5); // for all non-promoted products pages $for_product5 = array($product1, $product2, $product3, $product4); // for Product 5 page $for_product4 = array($product1, $product2, $product3, $product5); // for Product 4 page $for_product3 = array($product1, $product2, $product4, $product5); // for Product 3 page $for_product2 = array($product1, $product3, $product4, $product5); // for Product 2 page $for_product1 = array($product2, $product3, $product4, $product5); // for Product 1 page shuffle($all_products); shuffle($for_product1); shuffle($for_product2); shuffle($for_product3); shuffle($for_product4); shuffle($for_product5); 

This way I can echo on each page only the items I want to be randomly shown on that page.

Yes, I know that there is probably a much better way of doing it but this gets me going for now.

Thanks for all of the help though.

Источник

Читайте также:  Как остановить выполнение кода php
Оцените статью