I want to get the index of an array without foreach. this is sample array
Array
(
[0] => Array
(
[gcr_distance] => 31.0
[gcr_id] => 23
)
[1] => Array
(
[gcr_distance] => 28.0
[gcr_id] => 22
)
[2] => Array
(
[gcr_distance] => 26.0
[gcr_id] => 20
)
[3] => Array
(
[gcr_distance] => 110.0
[gcr_id] => 21
)
)
suppose if my data is gcr_id=21, by comparing with the above array it should give me an index of array 3
You can use a combination of array_search and array_column. array_column returns all the values which have a key of 'gcr_id' and then array_search returns the key which corresponds to a value of 21.
$array = array(
array('gcr_distance' => 31.0, 'gcr_id' => 23),
array('gcr_distance' => 28.0, 'gcr_id' => 22),
array('gcr_distance' => 26.0, 'gcr_id' => 20),
array('gcr_distance' => 110.0, 'gcr_id' => 21)
);
$key = array_search(21, array_column($array, 'gcr_id'));
echo $key;
Output:
3
Inspired by #Elementary's comment, I did some bench testing on this. What I found was that on a 100k entry array, array_search and array_column took around 80% of the time that a foreach based search took when the entry was not in the array, 95% of which was in the call to array_column. So it would seem that on average, a foreach based search would be faster.
Related
I have 2 arrays which are in the same form as below; for examples sake, lets call them $array1 and $array2
Array (
[Element1] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
[Element2] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
[Element3] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
)
What I need to do is take Element2 from the first array and then insert it into array2 as NewElement2
I have the following below but it keeps returning nothing at all in array2
$searchArray = array_search('Element2', $array1);
array_splice($array2, $searchArray, 1, array('NewElement2'));
Any help would be greatly appreciated.
for assign the value you can simply
$array2['Element2'] = $array1['Element2'];
(this append or repalce the entry for Elemet2 in $array2)
and for remove the value
unset($array1['Element2']);
This question already has answers here:
Print the keys of an array
(8 answers)
Closed 10 months ago.
Here is the array:
$campaigns =
Array (
[252] =>Array (
[campaign_type_id] => 9
[company] => Array (
[company_name] => facebook
[company_type] => 2
)
[campaign] => Array(
[pitch_id] => 27
[pitch_campaign_title] => facebook mandate
[pitch_campaign_description] => desc face
[pitch_campaign_image] => db.png
)
[title] => Accelarator
[selection] => Array (
[0] => Array(
[ca_mandate_id] => 96
[ca_id] => 252
[ca_company_id] => 1
[ca_updated] => 2015-12-31 12:37:50
)
)
[campaign_created_by] => 3
[userinfo] => Array (
[0] => Array (
[user_id] => 3
[user_first_name] => CoLabs
[user_last_name] => Accelerator
[user_img] => index2.jpg
[user_designation_name] => Investor
[user_company_id] => 123
)
)
)
)
how can I get the value '252'? Its a dynamic value.
I want to get whatever value is stored in place of 252.
Please help?
Thanks in advance.
Use the array_keys function: http://php.net/array_keys
array_keys — Return all the keys or a subset of the keys of an array
Description array array_keys ( array $array [, mixed $search_value = null [, bool $strict = false ]] )
For your code:
$keys = array_keys($campaigns);
Try array_keys
array_keys() returns the keys, numeric and string, from the array.
$req_key = array_keys($campaigns);
You can use array_keys() (as other suggested) and key() functions for getting this result.
Difference is that:
If you want to use array_keys() function it will returns you an array that consist of all keys.
If you want to use key() function it will returns you the first index of array. (you can get all keys by using loop);
Example 1 (With array_keys):
$arry = array(1,2,3);
echo "<pre>";
print_r(array_keys($arry));
Result:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
Example 2 (With key):
$arry = array(1,2,3);
echo key($arry);
Result:
0 // index
I have tried array_merge, to merge them based on similar keys, array_push, various [] combinations but I just can't figure this one out. I have two arrays, one looks like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
)
And, I want to add one new key to each of 650, 651, 652... sub-arrays (I will call the key 'Barva'), and short set of values from another array (10 total) to periodically loop in each sub-array under that key, so that 1st and 11th value is the same, 2nd and 12th is the same and so on, and all to be under the same key.
It would look like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
[Barva] => 1
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
[Barva] => 2
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
[Barva] => 3
)
...
[660] => Array
(
[Kampan] => ...
[ZelvaUL] => ...
[ZelvaOV] => ...
[OCS] => ...
[Rezim] => ...
[Barva] => 1
)
Seriously, I am out of ideas...
Thanks for any help guys.
edit:
This is the array I want to add:
$camp_barvy = array(
'background-color:#ffffff;color:#111111;',
'background-color:#ffcc02;color:#111111;',
'background-color:#ff7700;color:#ffffff;',
'background-color:#ff2323;color:#ffffff;',
'background-color:#ff00aa;color:#ffffff;',
'background-color:#aa44ff;color:#ffffff;',
'background-color:#1188ff;color:#ffffff;',
'background-color:#11ddff;color:#111111;',
'background-color:#00dd77;color:#111111;',
'background-color:#119911;color:#ffffff;'
);
I wanna do some large and extensive conditioned formatting and both javascript and php if statement make the loading too slow, so I figured I will make the format part of the array I already look in for the values based on which I choose the desired format.
Really, its the best choice :)
What you want to do is iterate over each value in your "input" array and insert in it a new value taken from your "data" array (those 10 values you mention). When your data array is exhausted, you want to loop back to its start and continue inserting values in the "input" array elements.
So you want something like:
foreach ($input as &$row) {
$row['Brava'] = $next_item_from_data_array;
}
which leaves just the problem of how to easily iterate and loop over the data array.
A convenient and modern way of doing this is by using the built-in SPL iterators: an ArrayIterator for your data array and an InfiniteIterator around that so that you loop back to the start automatically as required. This way you also don't have to assume anything about your data array (such as if it is numerically indexed or not).
For example:
$dataIterator = new InfiniteIterator(new ArrayIterator($data));
$dataIterator->rewind();
foreach ($input as &$row) {
$row['Brava'] = $dataIterator->current();
$dataIterator->next();
}
// After iterating by reference (&$row) it is always a good idea to unset
// the reference so that you don't reuse it later on by mistake -- although
// this is not required and the program will work correctly without it.
unset($row);
See it in action.
I have an multidimensional array:
Array
(
[0] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Other Cereals
[IName] =>
[Date] => 2013-02-05
)
[1] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar
[Date] => 2013-02-06
)
[2] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
[Date] => 2013-02-05
)
)
And I am trying to use array unique to filter this
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
I am having no luck. How can I filter the duplicates?
Cheers.
If you filter input and therefore don't have extra spaces in IName field, you can use something as simple as this for filtering:
$array[2]['IName'] = implode(',', array_unique(explode(',', $array[2]['IName'])));
The problem is that you habe in array two Oats,Milk,Sugar as element of IName, in array three you have Oats,Milk,Sugar,Oats,Milk,Sugar. This is not the same!
"Oats,Milk,Sugar"=="Oats,Milk,Sugar,Oats,Milk,Sugar" (or "Oats,Milk,Sugar".equals("Oats,Milk,Sugar,Oats,Milk,Sugar")) is false.
If you want to have it unique you have to explode the single results and then do a unique on it or you have to store the single values in seperate fields...
BTW: Here is a link how to remove duplicates from a multi dimensional array How to remove duplicate values from a multi-dimensional array in PHP
I am not sure if a function exists for that, here is a simple solution,
you can loop the array, and get the result of each value, then explode result, and insert it into an array.
then use the array_unique function.
try this:
$result = array();
foreach($arrays as $array)
{
$tmp = $array['IName'];
$tmp2 = explode(',',$tmp);
foreach ($tmp2 as $t)
{
$result[]=$t;
}
}
$array_unique = array_unique($result);
I have this multidimensional array:
Array
(
[0] => Array
(
[0] => 2012-02-26 07:15:00
)
[1] => Array
(
[0] => 2012-02-26 17:45:00
[1] => 2012-02-26 18:55:00
)
[2] => Array
(
[0] => 2012-02-26 18:55:00
[1] => 2012-02-26 17:45:00
)
[3] => Array
(
[0] => 2012-02-26 18:57:00
[1] => 2012-02-26 17:45:00
[2] => 2012-02-26 18:55:00
)
When I count subarrays I get this 1,2,2,3. How could I receive it in 3,2,2,1? I need to get for example last 3 subarrays with the highest subarray count (DESC, it means 3,2,2). How can I achieve this?
You can achieve it by utilizing usort function.
function cmp($a, $b){
return (count($b) - count($a));
}
usort($array, 'cmp');
$highest_3_sub_arrays = array_slice($array, 0, 3);
This might be what you seek:
natsort($sub_count);
$rev = array_reverse($sub_count);
$result = array_pad($rev, 3);
You might want to omit the actual sorting if the values you have are already in order.
$sizes=array();
foreach ($myarray as $k=>$v)
if (!is_array($v)) $sizes["$k"]=0;
else $sizes["$k"]=sizeof($v);
sort($sizes);
echo array_pop($sizes); //outputs 3
echo array_pop($sizes); //outputs 2
echo array_pop($sizes); //outputs 2
It seems to me that all of the other answers are working too hard. usort(), count(), and foreach() aren't necessary and when I tried natsort() it gave me: <b>Notice</b>: Array to string conversion in <b>[...][...]</b>.
rsort() will put the longest subarrays first.
Code:
$array=array(
["2012-02-26 18:55:00","2012-02-26 17:45:00"],
["2012-02-26 07:15:00"],
["2012-02-26 18:57:00","2012-02-26 17:45:00","2012-02-26 18:55:00"],
["2012-02-26 17:45:00","2012-02-26 18:55:00"]
);
$size=3; // modify this line to declare how many subarrays to capture
rsort($array); // sort the subarrays in DESC order
var_export(array_slice($array,0,$size)); // print the first n subarrays
Output:
array (
0 =>
array (
0 => '2012-02-26 18:57:00',
1 => '2012-02-26 17:45:00',
2 => '2012-02-26 18:55:00',
),
1 =>
array (
0 => '2012-02-26 18:55:00',
1 => '2012-02-26 17:45:00',
),
2 =>
array (
0 => '2012-02-26 17:45:00',
1 => '2012-02-26 18:55:00',
),
)
If you want to implement some additional sorting to break the length-ties (like between your two 2-element subarrays), then you will need to specify that in your question.