count how many duplicate keys are in array of objects? - php

[
{
"playerId":3207,
"playerName":"RyanGarbutt",
"playerPos":"C",
"playerApiId":"5079"
},
{
"playerId":3238,
"playerName":"Max Domi",
"playerPos":"C",
"playerApiId":"5412"
},
{
"playerId":3240,
"playerName":"AnthonyDuclair",
"playerPos":"LW",
"playerApiId":"5441"
}
]
1-> I want to count playerPos(C,LW) occurrences?
2-> How to get data in format like[{"c":"2"},{"LW":"1"}]

You can use array_reduce
$arr = '[{"playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{"playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{"playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';
$arr = json_decode( $arr, true );
$result = array_reduce( $arr , function( $c, $v ) {
isset( $c[ $v[ "playerPos" ] ] ) ? $c[ $v[ "playerPos" ] ]++ : $c[ $v[ "playerPos" ] ] = 1;
return $c;
}, array() );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[C] => 2
[LW] => 1
)
Doc: http://php.net/manual/en/function.array-reduce.php

Without loop, conditions and callback function.
$arr = '[{"playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{"playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{"playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';
$arr = json_decode( $arr, true );
$result = array_count_values(array_column($arr,"playerPos"));
print_r($result);
Output
Array (
[C] => 2
[LW] => 1
)
Working example
Demo

You can try something like this :
1/ First, create two var you will use as counter of occurences of "C" and "LW" :
$C = 0;
$LW = 0;
2/ Loop through your array with a foreach loop and test each time if the value of your obj for the key "playerPos" is equal to "C" or "LW", then add +1 for your counter var :
foreach($array as $obj) {
$test = $obj['playerPos'];
if ($test == "C")
$C++;
else if ($test == "LW")
$LW++;
}
3/ Then you need to check the value of each var to know the number of occurences.
Is this what you are looking for?

function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$data =
'[{
"playerId":3207,"playerName":"RyanGarbutt","playerPos":"C","playerApiId":"5079"},{
"playerId":3238,"playerName":"Max Domi","playerPos":"C","playerApiId":"5412"},{
"playerId":3240,"playerName":"AnthonyDuclair","playerPos":"LW","playerApiId":"5441"}]';
$data=json_decode($data,true);
$uniqueArray = unique_multidim_array($data,'playerPos');
print_r($uniqueArray);
print_r(count($uniqueArray));

Related

Combine two arrays two one and set keys

I have been struggling with this for quite some time. I have two arrays, which I need to combine.
This is my input:
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
Now the structure is, that each item in each array follows each other. So, the result should be something like:
{
"result": [
{
"mrn" : "18DK00310020B11A84",
"shipper" : "1861575"
},
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
]
}
However I simply cannot figure out how to do this.
I have tried to merge the two original arrays:
//Input
$array_one = $request->array_one;
$array_two = $request->array_two;
//Merge the two received arrays
$final = array_merge_recursive($array_one, $array_two);
However, this just removes array_one and array_two, but the array is still split up.
How can I combine above array, so it will have below format:
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
You can do this with some custom code:
$array_one = $request->array_one;
$array_two = $request->array_two;
$final = array_map(function ($value, $key) use ($array_two) {
foreach ($value as $k => $v) {
return [
"mrn" => $v,
"shipper" => array_get($array_two, "shipperreference.$key.$k")
];
}
}, array_get($array_one, 'mrnreference'), array_keys(array_get($array_one, 'mrnreference')));
A very quick solution to this would be just to iterate through a for loop.
for($i = 0; $i < count($array_one); $i++){
$final[$i]["mrn"] = $array_one["mrnreference"][$i]; // Mrn key equals array one value
$final[$i]["shipping"] = $array_two["shipperreference"][$i]; // Shipping key equals array two value
}
However, this has a small caveat that it could lead to an error, if $array_one and $array_two are not the same size.
First of all array_map can be used to get the values and then in simple for loop you can combine them. Notice that the size of mrnreference and shipperreference must be the same otherwise it will pop notice
$json = '
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
';
$arr = json_decode($json, true);
$ref = array_map(function($e){return $e['key_0'];}, $arr['array_one']['mrnreference']);
$ship = array_map(function($e){return $e['key_0'];}, $arr['array_two']['shipperreference']);
$output = array();
for ($i = 0, $cnt = count($ref); $i < $cnt ; ++$i) {
$output[] = [
'mrn' => $ref[$i],
'shipper' => $ship[$i],
];
}
echo json_encode(['result' => $output]);

PHP make a multidimensional associative array from key names in a string separated by brackets

I have a string with a variable number of key names in brackets, example:
$str = '[key][subkey][otherkey]';
I need to make a multidimensional array that has the same keys represented in the string ($value is just a string value of no importance here):
$arr = [ 'key' => [ 'subkey' => [ 'otherkey' => $value ] ] ];
Or if you prefer this other notation:
$arr['key']['subkey']['otherkey'] = $value;
So ideally I would like to append array keys as I would do with strings, but that is not possible as far as I know. I don't think array_push() can help here. At first I thought I could use a regex to grab the values in square brackets from my string:
preg_match_all( '/\[([^\]]*)\]/', $str, $has_keys, PREG_PATTERN_ORDER );
But I would just have a non associative array without any hierarchy, that is no use to me.
So I came up with something along these lines:
$str = '[key][subkey][otherkey]';
$value = 'my_value';
$arr = [];
preg_match_all( '/\[([^\]]*)\]/', $str, $has_keys, PREG_PATTERN_ORDER );
if ( isset( $has_keys[1] ) ) {
$keys = $has_keys[1];
$k = count( $keys );
if ( $k > 1 ) {
for ( $i=0; $i<$k-1; $i++ ) {
$arr[$keys[$i]] = walk_keys( $keys, $i+1, $value );
}
} else {
$arr[$keys[0]] = $value;
}
$arr = array_slice( $arr, 0, 1 );
}
var_dump($arr);
function walk_keys( $keys, $i, $value ) {
$a = '';
if ( isset( $keys[$i+1] ) ) {
$a[$keys[$i]] = walk_keys( $keys, $i+1, $value );
} else {
$a[$keys[$i]] = $value;
}
return $a;
}
Now, this "works" (also if the string has a different number of 'keys') but to me it looks ugly and overcomplicated. Is there a better way to do this?
I always worry when I see preg_* and such a simple pattern to work with. I would probably go with something like this if you're confident in the format of $str
<?php
// initialize variables
$str = '[key][subkey][otherkey]';
$val = 'my value';
$arr = [];
// Get the keys we want to assign
$keys = explode('][', trim($str, '[]'));
// Get a reference to where we start
$curr = &$arr;
// Loops over keys
foreach($keys as $key) {
// get the reference for this key
$curr = &$curr[$key];
}
// Assign the value to our last reference
$curr = $val;
// visualize the output, so we know its right
var_dump($arr);
I've come up with a simple loop using array_combine():
$in = '[key][subkey][otherkey][subotherkey][foo]';
$value = 'works';
$output = [];
if(preg_match_all('~\[(.*?)\]~s', $in, $m)) { // Check if we got a match
$n_matches = count($m[1]); // Count them
$tmp = $value;
for($i = $n_matches - 1; $i >= 0; $i--) { // Loop through them in reverse order
$tmp = array_combine([$m[1][$i]], [$tmp]); // put $m[1][$i] as key and $tmp as value
}
$output = $tmp;
} else {
echo 'no matches';
}
print_r($output);
The output:
Array
(
[key] => Array
(
[subkey] => Array
(
[otherkey] => Array
(
[subotherkey] => Array
(
[foo] => works
)
)
)
)
)
Online demo

Iterate a PHP array from a specific key

I know how to iterate an array in PHP, but I want to iterate an array from a specific key.
Assume that I have a huge array
$my_array = array(
...
...
["adad"] => "value X",
["yy"] => "value Y",
["hkghgk"] => "value Z",
["pp"] => "value ZZ",
...
...
)
I know the key where to start to iterate ("yy"). Now I want to iterate only from this key to another key.
I know that I don't want to do this:
$start_key = "yy";
foreach ($my_array as $key => $v)
{
if ($key == $start_key)
...
}
I was looking for Iterator, but I don't think this is what I need.
Try combining array_search, array_key, and LimitIterator. Using the example from the LimitIterator page and some extra bits:
$fruitsArray = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry',
'd' => 'damson',
'e' => 'elderberry'
);
$startkey = array_search('d', array_keys($fruitsArray));
$fruits = new ArrayIterator($fruitsArray);
foreach (new LimitIterator($fruits, $startkey) as $fruit) {
var_dump($fruit);
}
Starting at position 'd', this outputs:
string(6) "damson" string(10) "elderberry"
There is a limit to this approach in that it won’t loop around the array until the start position again. It will only iterate to the end of an array and then stop. You would have to run another foreach to do the first part of the array, but that can be easily done with the code we already have.
foreach (new LimitIterator($fruits, 0, $startkey-1) as $fruit) {
var_dump($fruit);
}
This starts from the first element, up to the element before the one we searched for.
foreach always resets the array's array pointer. You just can't do that the way you imagine.
You still have a few ways. The foreach way is just skipping everything until you found the key once:
$start_key = "yy";
$started = false;
foreach ($my_array as $key => $v)
{
if ($key == $start_key) {
$started = true;
}
if (!$started) {
continue;
}
// your code
}
You could as well work with the array pointer and use the while (list($key, $v) = each($array)) method:
$start_key = "yy";
reset($array); // reset it to be sure to start at the beginning
while (list($key, $v) = each($array) && $key != $start_key); // set array pointer to $start_key
do {
// your code
} while (list($key, $v) = each($array));
Alternatively, you can just extract the array you want to iterate over like MarkBaker proposed.
Perhaps something like:
foreach(array_slice(
$my_array,
array_search(
$start_key,array_keys($my_array)
),
null,
true) as $key => $v) {}
Demo
You can use array_keys and array_search.
Like this:
$keys = array_keys( $my_array ); // store all of your array indexes in a new array
$position = array_search( "yy" ,$keys ); // search your starting index in the newly created array of indexes
if( $position == false ) exit( "Index doesn't exist" ); // if the starting index doesn't exist the array_search returns false
for( $i = $position; $i < count( $keys ); $i++ ) { // starting from your desired index, this will iterate over the rest of your array
// do your stuff to $my_array[ $keys[ $i ] ] like:
echo $my_array[ $keys[ $i ] ];
}
Try it like this:
$startkey = array_search('yy', array_keys($my_array));
$endkey = array_search('zz', array_keys($my_array));
$my_array2 = array_values($my_array);
for($i = $startkey; $i<=$endkey; $i++)
{
// Access array like this
echo $my_array2[$i];
}
If this pull request makes it through, you will be able to do this quite easily:
if (seek($array, 'yy', SEEK_KEY)) {
while ($data = each($array)) {
// Do stuff
}
}

How can I get the data from an array that is returned by a method?

I have a method that does cool magical stuff and then returns my results in the form of an array.
So for instance
public function somemethod()
{
some stuff that builds an array
return $stuff;
}
If you do a
$s = stuff();
print_r($s->somemethod());
You get something like
array('a' => 'hi', 'b' => 'hello', 'c' => 'konnichiwa')
How can I access each array element?
$s->somemethod()->a?
$s->somemethod()['a'] ?
Use foreach:
foreach($s->somemethod() as $key => $value)
//process $key and $value
}
or 1 by 1:
$arr = $s->somemethod();
$arr['a']
// $arr['b']
// $arr['c']
You simply do this:
$a = $s->somemethod();
echo( $a[ "a" ] );
You have three options:
Access an element directly
$a = $s->somemethod();
echo $a['a'];
Loop over all elements
$a = $s->somemethod();
foreach ($a as $key => $value)
{
echo $key . ': ' $value
};
Move the elements into variables
list($a, $b, $c) = $s->somemethod();
function objectToArray( $object ){
if( !is_object( $object ) && !is_array( $object ) ){
return $object;}
if( is_object( $object ) ){
$object = get_object_vars( $object );}
return array_map( 'objectToArray', $object );}
NOTE: PHP 5.4 is not released yet now
In PHP 5.4 you can directly use the following:
echo $s->somemethod()['a'];

PHP Problem with array_count_values

I need to get one time occurence on my array, with my code I get only first result here is my example code:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
//do something...in this example i expect to receive b c and d
}
}
Thanks in advance
ciao h
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
echo $arr[$i];
}
}
That should display bcd
$arr=array("a","a","b","c","d");
$result = array();
$doubles = array();
while( !empty( $arr ) ) {
$value = array_pop( $arr );
if( !in_array( $value, $arr )
&& !in_array( $value, $doubles ) ) {
$result[] = $value;
}
else {
$doubles[] = $value;
}
}
May be you've miss your real results:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
/*
now $arrs is:
array (
'a' => 2,
'b' => 1,
'c' => 1,
'd' => 1,
)
*/
foreach($arrs as $id => $count){
if($count==1) {
// do your code
}
}
/*******************************************************/
/* usefull version */
/*******************************************************/
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach($arr as $id ){
if($arrs[$id]==1){
// do your code
echo "$id is single\n";
}
}
You just need to retrieve any value which only occurs once in the array, right? Try this:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach ($arrs as $uniqueValue => $count)
{
if($value == 1) {
echo $uniqueValue;
}
}
array_count_values returns an associative array where the key is the value found and its value is the number of times it occurs in the original array. This loop simply iterates over each unique value found in your array (i.e. the keys from array_count_values) and checks if it was only found once (i.e. that key has a value of 1). If it does, it echos out the value. Of course, you probably want to do something a bit more complex with the value, but this works as a placeholder.
$count = 0;
foreach(array("a","a","b","c","d") as $v){
if($v == 1){$count++;}
}

Categories