Say I have an array like this
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
How can I remove the first dimensional element if one of its 'post_title' or 'post_id' value is repeated?
Example:
Suppose we know that 'post_title' is '10' in two first dimensional elements.
How can I remove the repeated element from $posts?
Thanks.
Create a new array where you will store these post_title values. loop through $posts array and unset any duplicates. Example:
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
$tmp_array = array();
foreach ($posts as $i => $post)
{
if (!in_array($post['post_title'], $tmp_array)) // if it doesn't exist, store it
{
$tmp_array[] = $post['post_title'];
} else { // element exists, delete it
unset($posts[$i]);
}
}
Now in your $posts array you will have unique post_title values.
Related
I have a multidimensional array, consisting of products. Each sub-array has a product type. The productType is is in an array inside the Product array, such that;
0 => product [
productType [
id: 2
]
]
1 => product [
productType [
id: 1
]
]
2 => product [
productType [
id: 2
]
]
]
I need to remove an entire array element, if the id already exists, in this example, I would need to remove EITHER array[0] or array[2], it doesn't matter as I only need the productType[id] to populate the box.
I have made a loop that creates an array of the ID's that already exist, but it involves making 2 new arrays:
//This works but seems a bit inefficient
$productFinal = [];
$ids = [];
foreach ($products as $product) {
if (!in_array($product->getproductType()->getid(), $ids)) {
$productFinal[] = $product;
}
$ids[] = $product->getproductType()->getid();
}
I get the results I want, however I am sure that there is a more efficient way to do this, ideally using an inbuilt php function.
If you also get the key of each element, you could remove the element if necessary inside the foreach-loop:
$ids = [];
foreach ($products as $key => $product {
$id = $product->getproductType()->getid();
if (in_array($id, $ids)) {
unset($product[$key];
} else {
$ids[] = $id;
}
}
There is no need for a loop, you can use array_column to make the array associative, which will remove any duplicates.
Then use array_values to make the array indexed again.
$arr = array_values(array_column($arr, Null, "id"));
In my foreach loop, I am creating an array for each post I loop through. This array contains various post elements that I want to add to a new array and post back via ajax. I want to create a single array with multiple arrays inside that I can then encode and send. Each array looks like this and I'm looping through about 20 times.
$postdata = array(
'thumb'=>$thumb,
'title'=>$title,
);
What Im looking for is this:
array(
array(
'thumb'=>$thumb,
'title'=>$title,
)
array(
'thumb'=>$thumb,
'title'=>$title,
)
etc...
)
I tried array_merge but this didn't work. I'm guessing its something along the lines of:
$postsarray = array();
foreach($posts as $p){
$array = array('thumb'=>$thumb,'title'=>$title);
$postsarray[] = $array;
}
But that still didn't work. I got an empty array with no arrays inside.
I have an array with 45 object elements containing id, name, is_premium.
From MySQL I receive them, ordered by is_premium desc, and some of them have is_premium = 0 at the end of list.
How can I randomize elements with is_premium=1, keeping the is_premium=0 at the end of array?
Try if this works:
<?php
//assuming the array of objects is called $array
$new_array = array_merge(
shuffle(
array_filter($array,function($x){return $x['is_premium'] == 1;})
),
array_filter($array,function($x){return $x['is_premium'] == 0;})
);
?>
$inventory = array(
array("fruit"=>"orange", "price"=>3),
array("fruit"=>"kiwi", "price"=>2),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"apple", "price"=>3),
array("fruit"=>"orange", "price"=>3),
array("fruit"=>"banana", "price"=>10),
array("fruit"=>"banana", "price"=>10),
);
// what I wish to do is loop through this array and add all of the 'prices' for each
// unique key 'fruit' and then sort them afterwards
// ex. the output I wish to achieve would be an array as such:
$sum_array = array("banana"=>"20", "apple"=>"9", "orange"=>"6", "kiwi"=>"2");
Well, just group them by fruit and then sort the end-result:
function groupFruits(&$result, $item)
{
$key = $item['fruit'];
#$result[$key] += $item['price'];
return $result;
}
$grouped = array_reduce($inventory, 'groupFruits', array());
arsort($grouped);
print_r($grouped);
Demo
See also: array_reduce() arsort()
Update
You will see some crazy results when you look at this code in different versions of PHP.
I'm retrieving some hierarchical data from an Oracle database using the "connect by" function.
Then I populate a PHP array with the result of my query looking like:
while ($row_branches = oci_fetch_array($query_tree)) {
$tree[] = array(
'id' => $row_branches['ID']
, 'parent' => $row_branche['PARENT']
, 'data' => htmlspecialchars($row_branches['NAME'])
, 'level' => $row_branches['LEVEL']
);
}
The field ID is the unique id of the row
The field PARENT is the ID of the parent
The field DATA is the name of the item
The field LEVEL is the level of the row in the hierarchy.
I'd rather have a multidimensional array because my goal is to use the PHP function json_decode().
The depth of the hierarchy is never known in advance.
So my question is:
How could I populate a multidimensional array with the result of my query?
Thanks a million in advance for your answers.
try this
function adj_tree(&$tree, $item) {
$i = $item['ID'];
$p = $item['PARENT'];
$tree[$i] = isset($tree[$i]) ? $item + $tree[$i] : $item;
$tree[$p]['_children'][] = &$tree[$i];
}
$tree = array();
while ($row = oci_fetch_array($query_tree)) {
adj_tree($tree, $row);