I have the following array:
$names = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");
and want to output all keys and unique values.
The result should be:
Peter: Accounting
Joe: Finance, Human Resource
Thanks Philip
Create an empty array to hold the end result and use a simple foreach loop like this;
$names = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");
$resultArr = array();
foreach($names as $key => $value){
$resultArr[$value][] = $key;
}
// display $resultArr array
var_dump($resultArr);
Here's a live demo
Iterate through the keys and values in the array using a foreach loop and print both the keys and values.
foreach($names as $key => $value) {
print "$key : $value\n";
}
Related
I've 2 array in php
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
This is a result of select query wrote in codeigniter. so that is associative array. This is 2 query result one is for user list and second is for invited user list. I want check in user list which user is invited. So that I want to compare that array
foreach ($array1 as $key => $value) {
if($array2[$key]->invite_user_id==$value->user_id) {
echo "Matched";
}
}
but it compare only 2 value of array1 with array2 3rd value is not compare. How it could compare all value of array1 and array2 in above foreach loop
I found that answer
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
$invitationset = [];
foreach ($array2 as $invite) {
$invitationset[$invite->invite_user_id] = $invite->invite_user_id;
}
foreach ($array1 as $key => $value) {
if(isset($invitationset[$value->user_id])){
if($invitationset[$value->id]==$value->user_id){
echo "Matched";
}
}
}
In your assoc arrays you have dublicate keys. So if you use:
print_r( $array1 );
You'll see that your array only contains the last entry:
Array ( [user_id] => 3 )
I think that is not what you have expected. So you have to use different keys like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
Or you even dont use assoc arrays because it is obsolete in your example but never mind:
$user_ids = array('1','2','3');
$invited_user_ids = array('1','3');
You can compare your assoc arrays like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
foreach ($array1 as $user_id) {
if( in_array( $user_id, $array2 ) ) {
echo "Matched id: $user_id";
}
}
I have two arrays namely arr and arr2.
var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}];
var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];
Is it possible to get array below shown from above two arrays?
result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];
If i use array_merge then i get answer as
result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];
You must decode JSON to arrays, manually merge them and again encode it to JSON :)
<?php
$arr = json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]', true);
$arr2 = json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]', true);
$result = [];
foreach ($arr as &$item) {
if (empty($arr2))
break;
foreach ($arr2 as $key => $item2) {
if ($item['month'] === $item2['month']) {
$item = array_merge($item, $item2);
unset($arr2[$key]);
continue;
}
}
}
if (!empty($arr2))
$arr = array_merge($arr, $arr2);
echo json_encode($arr);
The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.
But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.
Here is a one-liner that doesn't use foreach() loops or if statements:
Code: (Demo)
$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true);
$arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true);
echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));
Output:
[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]
The breakdown:
echo json_encode( // convert back to json
array_values( // remove the temp keys (reindex)
array_replace_recursive( // effectively merge/replace elements associatively
array_column($arr,NULL,'month'), // use month as temp keys for each subarray
array_column($arr2,NULL,'month') // use month as temp keys for each subarray
)
)
);
You should write your own function to do that
$res = [];
foreach ($arr as $item) {
$res[$item['month']] = $item;
}
foreach ($arr2 as $item) {
$res[$item['month']] = isset($res[$item['month']]) ? array_merge($res[$item['month']], $item) : $item;
}
var_dump($res);
I have an array where I store key-value pair only when the value is not null. I'd like to know how to retrieve keys in the array?
<?php
$pArray = Array();
if(!is_null($params['Name']))
$pArray["Name"] = $params['Name'];
if(!is_null($params['Age']))
$pArray["Age"] = $params['Age'];
if(!is_null($params['Salary']))
$pArray["Salary"] = $params['Salary'];
if(count($pArray) > 0)
{
//Loop through the array and get the key on by one ...
}
?>
Thanks for helping
PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy:
foreach ($pArray as $key => $value)
{
print $key
}
//if you wanted to just pick the first key i would do this:
foreach ($pArray as $key => $value)
{
print $key;
break;
}
An alternative to this approach is to call reset() and then key():
reset($pArray);
$first_key = key($pArray);
It's essentially the same as what is happening in the foreach(), but according to this answer there is a little less overhead.
Why not just do:
foreach($pArray as $k=>$v){
echo $k . ' - ' . $v . '<br>';
}
And you will be able to see the keys and their values at that point
array_keys function will return all the keys of an array.
To obtain the array keys:
$keys = array_keys($pArray);
To obtain the 1st key:
$key = $keys[0];
Reference : array_keys()
Here I am Having an Issue:
I have two arrays like the following:
$array1 = array('1','2','1','3','1');
$array2 = array('1','2','3'); // Unique $array1 values
with array2 values i need all keys of an array1
Expected Output Is:
1 => 0,2,4
2 => 1
3 => 3
here it indicates array2 value =>array1 keys
Just use a loop:
$result = array();
foreach ($array1 as $index => $value) {
$result[$value][] = $index;
}
If you pass array_keys a 2nd parameter, it'll give you all the keys with that value.
So, just loop through $array2 and get the keys from $array1.
$result = array();
foreach($array2 as $val){
$result[$val] = array_keys($array1, $val);
}
The following code will do the job. It will create a result array in which the attribute val will contain the value that is searched in array and keys attribute will be an array that contains the found keys. Based on your values following is an example:
$array1 =array('1','2','1','3','1');
$array2 =array('1','2','3');
$results = array();
foreach ($array2 as $key2=>$val2) {
$result = array();
foreach ($array1 as $key1=>$val1 ) {
if ($val2 == $val1) {
array_push($result,$key1);
}
}
array_push($results,array("val"=>$val2,keys=>$result ));
}
echo json_encode($results);
The result will be:
[{"val":"1","keys":[0,2,4]},
{"val":"2","keys":[1]},
{"val":"3","keys":[3]}]
I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.