replace duplicate fom stdclass array php [duplicate] - php

This question already has answers here:
How can I remove duplicates in an object array in PHP?
(2 answers)
Closed 8 years ago.
When I print $online_performers variable I want to get a unique value for id 2. Do I need to convert them in standard array first or is that possible without it? (remove all duplicates).Please check my new code for this.
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[2] => stdClass Object
(
[id] => 2
[username] => Sample1
)
[3] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)
to
Array
(
[0] => stdClass Object
(
[id] => 1
[username] => Sample1
)
[1] => stdClass Object
(
[id] => 4
[username] => Sample4
)
)

PHP has a function called array_filter() for that purpose:
$filtered = array_filter($array, function($item) {
static $counts = array();
if(isset($counts[$item->id])) {
return false;
}
$counts[$item->id] = true;
return true;
});
Note the usage of the static keyword. If used inside a function, it means that a variable will get initialized just once when the function is called for the first time. This gives the possibility to preserve the lookup table $counts across multiple function calls.
In comments you told, that you also search for a way to remove all items with id X if X appears more than once. You could use the following algorithm, which is using a lookup table $ids to detect elements which's id occur more than ones and removes them (all):
$array = array("put your stdClass objects here");
$ids = array();
$result = array();
foreach($array as $item) {
if(!isset($ids[$item->id])) {
$result[$item->id]= $item;
$ids[$item->id] = true;
} else {
if(isset($result[$item->id])) {
unset($result[$item->id]);
}
}
}
$result = array_values($result);
var_dump($result);

If you don't care about changing your keys you could do this with a simple loop:
$aUniq = array ();
foreach($array as $obj) {
$aUniq[$obj->id] = $obj;
}
print_r($aUniq);

Let's say we have:
$array = [
//items 1,2,3 are same
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
Then duplication depends of what do you mean. For instance, if that's about: two items with same id are treated as duplicates, then:
$field = 'id';
$result = array_values(
array_reduce($array, function($c, $x) use ($field)
{
$c[$x->$field] = $x;
return $c;
}, [])
);
However, if that's about all fields, which should match, then it's a different thing:
$array = [
//1 and 3 are same, 2 and 3 are not:
(object)['id'=>1, 'username'=>'foo'],
(object)['id'=>2, 'username'=>'bar'],
(object)['id'=>2, 'username'=>'baz'],
(object)['id'=>2, 'username'=>'bar']
];
You'll need to identify somehow your value row. Easiest way is to do serialize()
$result = array_values(
array_reduce($array, function($c, $x)
{
$c[serialize($x)] = $x;
return $c;
}, [])
);
But that may be slow since you'll serialize entire object structure (so you'll not see performance impact on small objects, but for complex structures and large amount of them it's sounds badly)
Also, if you don't care about keys in resulting array, you may omit array_values() call, since it serves only purpose of making keys numeric consecutive.

Related

How to split array into all possible combinations

How can I loop through an array, split it into two arrays and run a function for each possible combination? Order does not matter.
// Original array
$array = array('a','b','c','d','e');
// Result 1
array('a');
array('b','c','d','e');
// Result 2
array('a', 'b');
array('c','d','e');
// Result 3
array('a', 'c');
array('b','d','e');
And so on...
Here's my take at this:
<?php
$ar = ['a','b','c','d','e'];
function permuteThrough($ar, $callback, $allowMirroredResults = true, $mode = 'entry', $desiredLeftCount = null, $left = [], $right = [])
{
switch($mode)
{
case 'entry':
// Logic:
// Determine how many elements we're gonna put into left array
$len = $allowMirroredResults ? count($ar) : floor(count($ar)/2);
for($i=0; $i <= $len; $i++)
{
call_user_func(__FUNCTION__, $ar, $callback, $allowMirroredResults, 'permute',$i);
}
break;
case 'permute':
// We have nothing left to sort, let's tell our callback
if( count($ar) === 0 )
{
$callback($left,$right);
break;
}
if( count($left) < $desiredLeftCount )
{
// Note: PHP assigns arrays as clones (unlike objects)
$ar1 = $ar;
$left1 = $left;
$left1[] = current(array_splice($ar1,0,1));
call_user_func(__FUNCTION__, $ar1, $callback, $allowMirroredResults, 'permute', $desiredLeftCount, $left1, $right);
}
// This check is needed so we don't generate permutations which don't fulfill the desired left count
$originalLength = count($ar) + count($left)+count($right);
if( count($right) < $originalLength - $desiredLeftCount )
{
$ar2 = $ar;
$right1 = $right;
$right1[] = current(array_splice($ar2,0,1));
call_user_func(__FUNCTION__, $ar2, $callback, $allowMirroredResults, 'permute', $desiredLeftCount, $left, $right1);
}
break;
}
}
function printArrays($a,$b)
{
echo '['.implode(',',$a).'],['.implode(',',$b)."]\n";
}
permuteThrough($ar, 'printArrays', true); // allows mirrored results
/*
[],[a,b,c,d,e]
[a],[b,c,d,e]
[b],[a,c,d,e]
[c],[a,b,d,e]
[d],[a,b,c,e]
[e],[a,b,c,d]
[a,b],[c,d,e]
[a,c],[b,d,e]
[a,d],[b,c,e]
[a,e],[b,c,d]
[b,c],[a,d,e]
[b,d],[a,c,e]
[b,e],[a,c,d]
[c,d],[a,b,e]
[c,e],[a,b,d]
[d,e],[a,b,c]
[a,b,c],[d,e]
[a,b,d],[c,e]
[a,b,e],[c,d]
[a,c,d],[b,e]
[a,c,e],[b,d]
[a,d,e],[b,c]
[b,c,d],[a,e]
[b,c,e],[a,d]
[b,d,e],[a,c]
[c,d,e],[a,b]
[a,b,c,d],[e]
[a,b,c,e],[d]
[a,b,d,e],[c]
[a,c,d,e],[b]
[b,c,d,e],[a]
[a,b,c,d,e],[]
*/
echo "==============\n"; // output separator
permuteThrough($ar, 'printArrays', false); // doesn't allow mirrored results
/*
[],[a,b,c,d,e]
[a],[b,c,d,e]
[b],[a,c,d,e]
[c],[a,b,d,e]
[d],[a,b,c,e]
[e],[a,b,c,d]
[a,b],[c,d,e]
[a,c],[b,d,e]
[a,d],[b,c,e]
[a,e],[b,c,d]
[b,c],[a,d,e]
[b,d],[a,c,e]
[b,e],[a,c,d]
[c,d],[a,b,e]
[c,e],[a,b,d]
[d,e],[a,b,c]
*/
My permuteThrough function takes three arguments.
The array, the callback, and an optional boolean indicating whether or not you want to allow mirrored results.
The logic is pretty straight forward:
First decide how many elements we want to put into our left array.
Then Recursively call the function like so:
Our working array with the remaining elements to sort.
Shift an element off and put it into the left array. The result gets sent to another layer of recursion.
Shift an element off and put it into the right array. The result gets sent to another layer of recursion.
If there's no elements left to shift off, call our callback with the resulting left and right arrays.
Finally, make sure we're not going over the desired left array element size determined by the for loop at the beginning and make sure the right size doesn't become so big that it makes the desired left size impossible to satisfy. Normally this would be done by two separate functions. One to decide how many elements should go into the left array. And one to be used for recursion. But instead I tossed in another argument to the recursion function to eliminate the need for a separate function so it can all be handled by the same recursive function.
This is the best I can do:
class Combos
{
/**
* getPossible then getDivide
*
* #param array $input
* #return array
*/
public function getPossibleAndDivided( array $input )
{
return $this->getMultiShiftAndDivided( $this->getPossible( $input ) );
}
/**
* return all possible combinations of input
*
* #param array $input
* #return array
*/
public function getPossible( array $inputs )
{
$result = [];
if ( count( $inputs ) <= 1 ) {
$result = $inputs;
} else {
$result = array();
foreach($inputs as $input){
//make it an array
$first = [ $input ];
//get all inputs not in first
$remaining = array_diff( $inputs, $first );
//send the remaining stuff but to ourself
$combos = $this->getPossible( $remaining );//recursive
//iterate over the above results (from ourself)
foreach( $combos as $combo ) {
$last = $combo;
//convert to array if it's not
if( !is_array( $last ) ) $last = [ $last ];
//merge them
$result[] = array_merge( $first, $last );
}
}
}
return $result;
}
/**
* shift and divide a multi level array
*
* #param array $array
* #return array
*/
public function getMultiShiftAndDivided( array $mArray )
{
$divided = [];
foreach ( $mArray as $array ) {
$divided = array_merge($divided, $this->getShiftAndDivided( $array ));
}
return $divided;
}
/**
* shift and divide a single level array
*
* #param array $array
* #return array
*/
public function getShiftAndDivided( array $array )
{
$divided = [];
$array1 = [];
while( count( $array ) ){
$array1[] = array_shift( $array );
$divided[] = [ $array, $array1 ];
}
return $divided;
}
}
How it works
Top level, I don't want to get into all the details. This is basically a 2 step process or at least it was easier to figure it out that way. I built it in a class to keep everything neat. It also allows better unit testing and re-usability.
This requires 2 operations, or at least it was easier for me to do it in 2 instead of as 1. They are combined in this method
public function getPossibleAndDivided( array $input )
{
return $this->getMultiShiftAndDivided( $this->getPossible( $input ) );
}
This is the main reason I made it a class, to keep everything packaged nicely together. I would call this a wrapper method.
Step One
$Combos->getPossible(array $input)
if only one item remains, return $inputs.
this is all the combinations it can ever have (its just a single element after all).
else It iterates thought $inputs with foreach as $input
Wraps $input as an array named $first
this is a single element from $inputs
Gets the remaining elements in $inputs in a non-destructive way as $remaining
using array_diff we need both elements as arrays (see aabove)
recursive call to $this->getPossible($remaining) (see #1) and returns as $combos
Iterates over $combos foreach as $combo
$combo is assigned to $last and turned into an array, if its not
sometimes combo is an array with several elements
sometimes is a single element. It depends on the recursive call
We add to our result set the merger of $first and $last
we need both as arrays so we can merge, without causing nesting
End Anything in $result is returned.
This basically rotates though all the combinations of the array and returns them in an array like this:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => e
[4] => d
)
[2] => Array
(
[0] => a
[1] => b
[2] => d
[3] => c
[4] => e
)
...
[117] => Array
(
[0] => e
[1] => d
[2] => b
[3] => c
[4] => a
)
[118] => Array
(
[0] => e
[1] => d
[2] => c
[3] => a
[4] => b
)
[119] => Array
(
[0] => e
[1] => d
[2] => c
[3] => b
[4] => a
)
)
Yes it returns 119 results, no I will not include them all.
Step Two
Don't forget the above output is a multi-dimensional array (this is important below).
$Combos->getMultiShiftAndDivided(array $mArray)
This method is intended to be used with multi-dimensional arrays (hence its name). We get this from "Step 1". Its basically a wrapper for $Combos->getShiftAndDivided($array)
Iterates over $mArray foreach as $array
It calls $this->getShiftAndDivided($array) returns and merges with $divided.
there was no need to store the results, so I didn't waste a variable on it.
Output example:
$input = array(array('a','b','c','d','e'));
print_r($combos->getMultiShiftAndDivided($input));
Array
(
[0] => Array
(
[0] => Array
(
[0] => b
[1] => c
[2] => d
[3] => e
)
[1] => Array
(
[0] => a
)
)
....
[4] => Array
(
[0] => Array
(
)
[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
)
)
$Combos->getShiftAndDivided(array $array)
This method is intended to be used single level arrays.
Loops as long as the count of $array is more then 0, while loop
$array1 gets the first element from $array added and that element is removed from $array (destructively)
we store both $array and $array1 in our results $divided
this records there current "state" at that moment
when there are no more items in $array we return our results
Output example:
$input = array('a','b','c','d','e');
print_r($combos->getShiftAndDivided($input));
Array
(
[0] => Array
(
[0] => Array
(
[0] => b
[1] => c
[2] => d
[3] => e
)
[1] => Array
(
[0] => a
)
)
....
[4] => Array
(
[0] => Array
(
)
[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
)
)
)
Basically this shifts the elements of a single array to two result arrays and records their state on each shift. I made it 2 functions so that it could be tested easier and be re-used easier.
Another issue is its kind of hard to check for multi-dimensional arrays. I know how to do it, but I didn't feel like it because it's kind of ugly and there is a better way. I say that because its possible to use a one level array in what is getMultiShiftAndDivided and it wouldn't give you what you would expect. Probably you would get an error like this:
//I say probably, but I actually test it ... lol
Warning: array_shift() expects parameter 1 to be array
Which could be confusing, one could think the code is buggered. So by having the second method call with a type set into it getShiftAndDivided( array $array ). When the wrapping method tries to call this with a string its going to blow up, but in a better way:
Catchable fatal error: Argument 1 passed to Combos::getShiftAndDivided() must be of the type array, string given
Hopefully that makes sense, it's something I always try to do in cases like this. It just makes life easier in the long run. Both function return the data in the same format, which is convenient (your welcome).
Summary
So the sum of what this does, is find all the combinations of our input, then it takes those and breaks each one into shifted and divided up array. There for it stands to reason that we will have all the possible combinations divided up into 2 arrays anyway possible. Because that is pretty much exactly what I said.
Now I am not 100% it does that, you can check them if you want, it returns like 599 elements at the end. So good luck on that, I would suggest testing just the results of $combos->getPossible($input). If that has all the combinations like it should, then this will have all that it needs. I am not sure if it returns duplicates, I don't think that was specified. But I didn't really check it.
You can call the main method like this:
$input = array('a','b','c','d','e');
print_r((new Combos)->getPossibleAndDivided($input));
Test It!
P.S. I spell breaks as brakes, but I can write code this, go figure...

array_column with an array of objects [duplicate]

This question already has answers here:
PHP. Is it possible to use array_column with an array of objects
(5 answers)
Closed 6 years ago.
TLDR; My question is different from PHP. Is it possible to use array_column with an array of objects. I want to only change the keys within the array and keep the objects, not having the objects' values stored in a separate array like the given answer.
I would like to set the keys, of an array with objects, to a value of the object. So this array:
$array = Array
(
[0] => stdClass Object
(
[id] = 12234
[value] = some value
)
[1] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Should become:
$array = Array
(
[12234] => stdClass Object
(
[id] = 12234
[value] = some value
)
[12994] => stdClass Object
(
[id] = 12994
[value] = some value
)
)
Now I could loop over the array, but I would prefer a more cleaner solution. I thought this should work:
$newArray = array_column($array, null, 'id');
The only problem is I'm having an array of objects instead of an array of arrays and I'm not using PHP7 yet. Now I found a similar question over here
PHP. Is it possible to use array_column with an array of objects
But the thing is it doesn't return what I expected. Cause this:
$newArray = array_map(function($o) {
return is_object($o) ? $o->id : $o['id'];
}, $array);
Returns
Array
(
[0] => 12234
[1] => 12994
)
Anyone who knows a clean solution (so without a for or foreach loop) for this?
$array = array_combine(array_map(function ($o) { return $o->id; }, $array), $array);
Whether this is really a lot better than a simple foreach loop, aside from "but, but, functional programming...!", is debatable.
// your data
$array = array(
(object) array(
"id" => "12234",
"value" => "some value",
),
(object) array(
"id" => "12235",
"value" => "some value",
),
(object) array(
"id" => "12236",
"value" => "some value",
),
);
// let's see what we have
print_r($array);
// here comes the magic ;-)
function key_flip_array($array, $keyname){
$keys = array_map(function($item, $keyname){
return (is_object($item) && isset($item->{$keyname}) ? $item->{$keyname} : (is_array($item) && isset($item[$keyname]) ? $item[$keyname] : null));
}, $array, array_fill(0, count($array), $keyname));
return array_combine($keys, $array);
}
$array = key_flip_array($array, "id");
// i hope this is what you wish to see
print_r($array);

simple search in multidimensional array

I have an array with the following values
- Array ( [id] => 3 [parent_id] => 2 [name] => Fitness )
- Array ( [id] => 4 [parent_id] => 3 [name] => Why do it)
- Array ( [id] => 5 [parent_id] => 3 [name] => Nutrition)
Id like to query it along the lines of
array_search([parent_id]='3', $array)
and return a list of matching elements. (In this instance it would be id's 4 & 5). I'm not sure if array_search() is the right way to go about this. May attempts are failing at moment.
<?php
function mySearchArr($key, $value, $myBigArr) {
$searchArr = array();
foreach($myBigArr as $smallArr)
if($smallArr[$key] == $value)
$searchArr[] = $smallArr;
return $searchArr
}
$matches = mySearchArr('parent_id', 3, $array);
?>
You could use array_filter with a custom callback
$lookup_id = 3;
$results = array_filter($your_array, function($arr) use ($lookup_id) {
return $your_array['parent_id'] == $lookup_id;
});
This code requires i believe >=PHP5.3, if you have an older version, you will have to implement the callback using either an actual defined function (normal php function), or using create_function

How to reduce the code for this function

Input array $items:
Array
(
[0] => Array
(
[id] => 2
)
[1] => Array
(
[id] => 5
)
)
Result of print_r(foo($items))
Array
(
[2] => 1
[5] => 1
)
Function foo()
function foo($items)
{
$result = array();
foreach($items => $array)
{
$result[$array['id']] = TRUE;
}
return $result;
}
How can I simply write this array transformation with standards PHP functions, like array_flip() or something else. Is it possible?
Using a built in PHP function would only introduce the unnecessary overhead of additional function calls. What you have written is already an efficient method for creating the desired output from the given input.
I would recommend using your custom function if possible.
$r = array_combine(
array_map(function($i){ return $i['id']; }, $items), // <-- key
array_fill(0, count($items), true /* or 1 */) // <-- value
);

Converting array and objects in array to pure array [duplicate]

This question already has answers here:
Convert a PHP object to an associative array
(33 answers)
Closed 1 year ago.
My array is like:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => demo1
)
[1] => stdClass Object
(
[id] => 2
[name] => demo2
)
[2] => stdClass Object
(
[id] => 6
[name] => otherdemo
)
)
How can I convert the whole array (including objects) to a pure multi-dimensional array?
Have you tried typecasting?
$array = (array) $object;
There is another trick actually
$json = json_encode($object);
$array = json_decode($json, true);
You can have more info here json_decode in the PHP manual, the second parameter is called assoc:
assoc
When TRUE, returned objects will be converted into associative arrays.
Which is exactly what you're looking for.
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
Just use this :
json_decode(json_encode($yourArray), true);
You can use array_walk to convert every item from object to array:
function convert(&$item , $key)
{
$item = (array) $item ;
}
array_walk($array, 'convert');
Assuming you want to get to this pure array format:
Array
(
[1] => "demo1",
[2] => "demo2",
[6] => "otherdemo",
)
Then I would do:
$result = array();
foreach ($array as $object)
{
$result[$object->id] = $object->name
}
(edit) Actually that's what I was looking for possibly not what the OP was looking for. May be useful to other searchers.
You should cast all objets, something like :
$result = array();
foreach ($array as $object)
{
$result[] = (array) $object
}
As you are using OOP, the simplest method would be to pull the code to convert itself into an array to the class itself, you then simply call this method and have the returned array populate your original array.
class MyObject {
private $myVar;
private $myInt;
public function getVarsAsArray() {
// Return the objects variables in any structure you need
return array($this->myVar,$this->myInt);
}
public function getAnonVars() {
// If you don't know the variables
return get_object_vars($this);
}
}
See: http://www.php.net/manual/en/function.get-object-vars.php for info on get_object_vars()
it you have object and you want to set a value as array
use
$this->object->pluck('name');
then you get the value as array of names like
["name1", "name2", "name3"];

Categories