How can I remove duplicate values from an array in PHP?
Answers
5
If you need to get entities as arrays instead of objects, you would need to use Doctrine's hydrator:
$em = $this->getDoctrine()->getManager();
$orgRepo = $em->getRepository('CompanyMyBundle:Org');
$entities = $orgRepo->createQueryBuilder('org')
->getQuery()
->getResult(DoctrineORMAbstractQuery::HYDRATE_ARRAY);
Note: I would suggest to leave entities as objects and use getters:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('CompanyMyBundle:Org')->findAll();
$tree = $this->treeBuilder($entities);
return array(
'entities' => $tree,
);
}
private function treeBuilder($entities, $pid = null)
{
$op = array();
/** Org $entity */ //Type hinting, if you use autocompletion
foreach ($entities as $entity) {
if ($entity->getParentId() == $pid) {
$op[$entity->getId()] = [
'Street' => $entity->getStreet(),
'ParentId' => $entity->getParentId()
];
$children = self::treeBuilder($entities, $entity->getId());
if (!empty($children)) {
$op[$entity->geId()]['children'] = $children;
}
}
}
return $op;
}
Saturday, May 29, 2021
3
Consider first splitting the keywords argument by spaces, then finding the unique values:
$posted = array_unique(explode(' ', str_replace("n", ' ', $posted)));
Saturday, May 29, 2021
3
Bit late, but may help someone looking for same answer. I used this very simple approach to;
- remove all the keys from nested arrays that contain no value, then
- remove all the empty nested arrays.
$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );
Friday, July 23, 2021
1
A quick way using array_reduce
would look like:
$unique = array_reduce($subject, function($final, $article){
static $seen = array();
if ( ! array_key_exists($article['fk_article_id'], $seen)) {
$seen[$article['fk_article_id']] = NULL;
$final[] = $article;
}
return $final;
});
Try a working example.
Edit: Seems you don't want to work with the aggregated results. Here are two other thoughts:
Filtering in PHP
$seen = array();
while ($row = pg_fetch_assoc($authors_result)) {
// Skip this row if we have already seen its article id
if (array_key_exists($row['fk_article_id'], $seen)) {
continue;
}
// Note that we have seen this article
$seen[$row['fk_article_id']] = NULL;
// Do whatever with your row
var_dump($row);
}
Filtering in the DB
The idea here is to change the query being executed so that the repeated article ids do not appear in the result set. How this is done will depend on the query that you're already using.
Friday, August 6, 2021
Only authorized users can answer the question. Please sign in first, or register a free account.
Use array_unique().
Example: