[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;
}
Related
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);
I have this simple array in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
When supplied with 'client corp', the output should be the above array with only the first item.
So far I have this:
$selectedTree = array_filter($tree,"checkForTags");
function checkForTags($var){
$arr = $var->tags;
$test = in_array("client corp", $arr, true);
return ($test);
}
However, the result is that it's not filtering. When I echo $test, I get 1 all the time. What am I doing wrong?
Something like this should do the trick:
$selectedTree = array_filter(array_map("checkForTags", $tree ,array_fill(0, count($tree), 'client corp')));
function checkForTags($var, $exclude){
$arr = $var->tags;
$test = in_array($exclude, $arr, true);
return ($test ? $var : false);
}
array_map() makes sure you can pass arguments to the array. It returns each value altered. So in the returning array, some values are present, others are set to false. array_filter() with no callback filters all falsey values from that array and you are left with the desired result
The in_array() function returns TRUE if needle is found in the array and FALSE otherwise. So by getting 1 as a result that means that "client corp" is found.
Check PHP in_array() manual
You can user array_search() to return the array key instead of using in_array().
i have this multidimensional array.
Array
(
[0] => Array
(
[car] => Toyota
)
[1] => Array
(
[car] => Ford
)
[2] => Array
(
[car] => Isuzu
)
[3] => Array
(
[car] => Chevrolet
)
)
i want to put them into indexed array like this..
Array = ("Toyota", "Ford", "Isuzu", "Chevrolet");
$result = array_map(function($item)
{ return $item['car']; }, $array);
Some functional approach. array_map
P.S. PHP has no indexed arrays
foreach($yourArray as $carArray)
{
$result[]=$carArray["car"];
}
And your understanding of indexed arrays is wrong. That example output you've shown contains all those values, not indexes, and since you didn't specify an index it will start from 0 and so on.
Option using array_map(), assuming your initial array is $arr
$new_arr = array_map(function($x){return $x['car'];}, $arr);
See demo
try using foreach and array_values, then save it into empty array. Hope it helps.
I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.
I have the following variable $rows:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH20
)
[2] => stdClass Object
(
[product_sku] => PCH19
)
[3] => stdClass Object
(
[product_sku] => PCH19
)
)
I need to create second array $second containing only unique values:
Array (
[0] => stdClass Object
(
[product_sku] => PCH20
)
[1] => stdClass Object
(
[product_sku] => PCH19
)
)
But when i run array_unique on $rows, i receive:
Catchable fatal error: Object of class stdClass could not be
converted to string on line 191
array_unique()
The optional second parameter sort_flags may be used to modify the sorting behavior using these values:
Sorting type flags:
SORT_REGULAR - compare items normally (don't change types)
SORT_NUMERIC - compare items numerically
SORT_STRING - compare items as strings
SORT_LOCALE_STRING - compare items as strings, based on the current locale.
Also note the changenotes below
5.2.10 Changed the default value of sort_flags back to SORT_STRING.
5.2.9 Added the optional sort_flags defaulting to SORT_REGULAR. Prior to 5.2.9, this function used to sort the array with SORT_STRING internally.
$values = array_unique($values, SORT_REGULAR);
$uniques = array();
foreach ($array as $obj) {
$uniques[$obj->product_sku] = $obj;
}
var_dump($uniques);
The default behavior of function array_unique() is to treat the values inside as strings first. So what's happening is that PHP is attempting to turn your objects into strings (which is throwing the error).
You can modify your function call like this:
$uniqueArray = array_unique($rows, SORT_REGULAR);
This will compare values without changing their data type.
Please check below code, I hope this will be helpful to you.
$resultArray = uniqueAssocArray($actualArray, 'product_sku');
function uniqueAssocArray($array, $uniqueKey)
{
if (!is_array($array))
{
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item)
{
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= false;
}
else
{
$replace=true;
}
if ($replace)
$uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}