I was wondering, is there something similar to array_count_values, but that works with objects ?
Let me explain:
array_count_values takes an array as argument, such as
[1]
Array (
[0] => banana
[1] => trololol
)
If i give that array to array_count_values, i will get something like:
[2]
Array (
[banana] => 1
[trololol] => 1
)
Now lets say that instead of strings, i have objects, that i want to count based on one of their properties. So i have:
[3]
Array (
[0] => stdClass Object (
[name] => banana
[description] => banana, me gusta!
)
[1] => stdClass Object (
[name] => trololol
[description] => trolololololol
)
)
And i'd want the magical-function-im-looking-for to count the number of objects with the same name property, returning the same input as [2]
Obviously i could easily do that on my own, but i was just wondering if there was a built-in function for that, since i couldnt seem to find one. Thanks, kind SOers!
No such function exists. You always need to first map the values you would like to count (and those values must be string or integer):
$map = function($v) {return $v->name;};
$count = array_count_values(array_map($map, $data));
Since PHP 7.0, you can use array_column for this.
$counts = array_count_values(array_column($array_of_objects, 'name'));
When this question was originally asked and answered array_column didn't exist yet. It was introduced in PHP 5.5, but it couldn't handle arrays of objects until 7.0.
Check out the Reflection classes to easily fetch information about your objects dynamically.
Related
I need to change array value based on specific value. Take a look at this array below :
Array
(
[0] => Array
(
[id] => 5
[title] =>
[nomor] => 1
)
[1] => Array
(
[id] => 6
[title] =>
[nomor] => 2
)
)
I need to change the array key based on nomor value. How can I do that?
You can use array_column for that (doc) as:
$arr = array_column($arr, null, "nomor");
Live example
The easiest way is to simply create a new array, loop through your existing one, and save each elements into the new one with the proper key.
foreach($array as $element) {
$formatted_array[$element['nomor']] = $element;
}
Here is a working fiddle:
https://3v4l.org/PlbJ1
Edit: Keep in mind though, if multiple elements have the same value as "nomor", the latest will override the previous one.
Edit 2: Per the other answer, PHP's array_column function seems to do this simpler.
I am working on a project to get the names of an array.
The arrays seem to be multidimensional, with the added bonus of being a stdclass Object. I am trying to select a key from the provided array but seem to have no luck selecting them.
echo($response->array[shoecompany]->array[1]->name);
from the information here
stdClass Object
(
[shoe] => shoemaker
[shoecompany] => Array
(
[0] => stdClass Object
(
[shoenumber] => 1
[name] => Blank
[1] => stdClass Object
(
[shoenumber] => 2
[name] => demo
)
[2] => stdClass Object
(
[shoenumber] => certificate
[name] => certofsale
)
)
)
Nothing i do seems to pull the information i need out of this. Any ways to go about pulling, said information.
The arrays seem to be multidimensional, with the added bonus of being a stdclass Object.
Arrays and objects aren't the same things.
I let you learn more about the specifics of both if you are curious.
Regarding access, yous use brackets - '[]' - when you want to access something in an array and an arrow - '->' - when you want to access an object's property :
$array['key'];
$object->property;
In your case, since only $response and the entries in the entry showcompany - I assume it's a typo - are objects, what you should write is :
$response->shoecompany[1]->name;
Which gives you in practical use :
foreach ($response->shoecompany as $val) {
echo $val->shoenumber, ' : ', $val->name, '<br>'; // Or whatever you want to print, that's for the sake of providing an example
}
If it is more convenient for you to handle exclusively arrays, you can also use get_object_vars() to convert an object properties to an array :
$response = get_object_vars($response);
Code should be like:
echo $response->shoecomapny[1]->name;
In short, to select key inside an object you need to use "->" operator and to select key inside array use "[]".
I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]
Just a quick one i need to get a value from an array the array is made like this
$resultOfAdd[“CaseAndMatterResult”][“ResultInfo”][“ReturnCode”];
and it gives an output of this
Array (
[AddCaseAndMatterResult] => Array (
[ResultInfo] => Array (
[ReturnCode] => OK
[Errors] =>
[Warnings] =>
)
[CaseID] => 4880062
[MatterID] => 4950481
[LeadID] => 0
[CustomerID] => 0
)
)
All i want to do is put the part "MatterID" into a variable. how would I achieve this.
i have tried
$matterID = array($resultOfAdd["MatterID"]);
and this does not work
Regards
This is a multi-dimensional, associative array. Think of it like floors of a building. The key MatterID does not live in the first dimension (floor), rather on the second, in the AddCaseAndMatterResult sub-array.
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID']
Successive dimensions of an array are specified with successive square-brackets, each naming the key to look in (this is true of most languages).
$matterID = $yourArray['AddCaseAndMatterResult']['MatterID'];
Use this way:
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID'];
I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.
All I'm looking for is the function that takes this:
Array
(
[0] => 1
[3] => 2
[4] => 3
[7] => 4
[9] => 5
)
And converts it into this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.
Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.
But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:
array_values() returns all the values from the input array and indexes numerically the array.
You can use array_merge:
$array = array_merge($array);
It will reindex values with numeric keys.
Update: Using array_values as proposed in #LostInTheCode's answer is probably more descriptive.
function array_reset_index_keys($array)
{
$return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}
And then use like a regular function, should re index the array
you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .