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);
Related
This question already has answers here:
Convert array of single-element arrays to a one-dimensional array
(8 answers)
Closed 3 years ago.
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.
I want to convert this array to single array like.
Convert this :-
Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
Convert To :-
Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
To "Merge" multiple arrays into one, you can use array_merge()
A good example would be:
$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);
Something like this should do:
while($row = $result->fetch_array(MYSQLI_NUM)) {
$users[] = $row[0];
}
Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.
$arr = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');
$one_dim_array = array_merge(...$arr);
//or better
$one_dim_array = array_column($arr,0);
echo "<pre>".var_export($one_dim_array, true);
Result:
array (
0 => 'user',
1 => 'user1',
2 => 'user2',
)
Try it yourself : Sandbox
Another alternative, aside from array_merge, for the case of an arbitrary number of subarrays, you could use array_reduce and build your final array:
$inArray = [['user'],['user1'],['user2'],['user3'],['user8'],['user7'],['user6']];
$inArray = array_reduce($inArray, function($arr, $elem){
$arr[] = $elem[0];
return $arr;
});
Of course, the straightforward solution would be to use array_merge:
$inArray = array_merge(...$inArray);
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.
[a] => Array (
[0] => MongoId Object (
[$id] => 506479dc9a5be1596b1bd97d
),
[1] => MongoId Object (
[$id] => 506479dc9a5be1596b1bd97d
)
)
I have an array like this one. I need to change the values to string, to change it to something like this:
array (
0 => "506479dc9a5be1596b1bd97d",
1 => "506479dc9a5be1596b1bd97d",
)
This is my solution, but it is expensive and I will be using this in a for loop.
$yut = implode(",", $a);
$arr = explode(",", $yut);
Are there any other solution?
You can just use array_map to call MongoId::__toString() which would convert all Mongo Object in your array to string
$list = array_map(function($var){ return $var->__toString(); }, $yourArray);
$new_array = array_map('strval', $array);
strval is php built in function that returns string value
like
function ($value){
return (string)$value;
}
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"];
A PHP question about arrays. Suppose we have two arrays:
[first] => Array
(
[0] => users
[1] => posts
[2] => comments
)
[second] => Array
(
[users] => the_users
[posts] => the_posts
[comments] => the_comments
[options] => the_options
)
How can I compare these two arrays? Meaning, how can we check whether or not the value in the first array is equal to the key in the second array (array_flip?) after combining them somehow (array_merge?). And whichever value/key pair matches, remove them from the array.
Basically, the end result would be the two arrays combined, duplicates removed, and the only index will be:
[third] => Array
(
[options] => the_options
)
try this:
$third = array_diff_key($second,array_flip($first));
There could be a built-in function for this, but if there isn't, try:
$third = array();
foreach(array_keys($second) as $item)
if(!in_array($item, $first))
$third[$item] = $second[$item];
Note that this assumes that $first will not have an item that doesn't have a corresponding key in $second. To account for this, you could have an additional loop (I don't know what you would set the value in $third to for these, maybe null:
foreach($first as $item)
if(!in_array($item, array_keys($second)))
$third[$item] = null;
This is pretty simple to do and this way is extremely efficient:
$third = $second;
foreach($first as $value)
{
if (isset($third[$value]))
{
unset($third[$value]);
}
}
this is the answer to ur question
$first= array
(
"0" => "users",
"1" => "posts",
"2" => "comments"
);
$firstf=array_flip($first);
$second = array
(
"users" => "the_users",
"posts" => "the_posts",
"comments" => "the_comments",
"options" => "the_options"
);
$third=array_diff_key($second,$firstf);
print_r($third);