PHP map named array to another named array - php

I have the following code for generating a new array:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language)
{
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
array_map('generateLanguageRules', $languages);
//Output:
array(
0 => array(
'seatsAllocatedForFrench' => 'numeric|max:300'
),
1 => array(
'seatsAllocatedForSpanish' => 'numeric|max:300'
),
2 => array(
'seatsAllocatedForGerman' => 'numeric|max:300'
),
3 => array(
'seatsAllocatedForChinese' => 'numeric|max:300'
)
)
I'm wondering if there is an easier way to output a flat array, instead of a nested one? I'm using Laravel. Are there maybe some helper functions that could do this?
UPDATE:
One possible Laravel specific solution:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
$c = new Illuminate\Support\Collection($languages);
$c->map(function ($language){
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
})->collapse()->toArray();

I dont know if laravel has a built-in method for that, (haven't used it yet). But alternatively, you could use RecursiveArrayIterator in conjunction to iterator_to_array() to flatten it and assign it. Consider this example:
$languages = array_keys(['French'=>4, 'Spanish'=>2, 'German'=>6, 'Chinese'=>8]);
function generateLanguageRules($language) {
return ["seatsAllocatedFor$language"=>"numeric|max:300"];
}
$data = array_map('generateLanguageRules', $languages);
$data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)));
echo "<pre>";
print_r($data);
echo "</pre>";
Sample Output:
Array
(
[seatsAllocatedForFrench] => numeric|max:300
[seatsAllocatedForSpanish] => numeric|max:300
[seatsAllocatedForGerman] => numeric|max:300
[seatsAllocatedForChinese] => numeric|max:300
)

Related

Use Dynamic Array inside Array PHP

I am new in PHP. I am working for send data using PHP API. Its method is like below
$createContact->setCustomFieldValues(
[
array(
'customFieldId' => 'pcVFD6',
'value' => array('35')
),
array(
'customFieldId' => 'pcVnzW',
'value' => array('37')
)
]
);
I have data in array like this
$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");
I want pass this values to above function but I am not getting idea about proper way to do it.
I have tried something like this
foreach ($aa as $key => $value){
$createContact->setCustomFieldValues([
array(
'customFieldId' => $key,
'value' => array($value)
)
]
);
}
its working but passing only last one array to API. Anyone here can please help me for achieve my goal?
Thanks!
You need to transform the array before you pass it to setCustomFieldValues. You don't want to be calling setCustomFieldValues multiple times as your current attempt does, as that's not equivalent to the original. You just need to change the structure of the array ahead of time.
For example:
$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");
$transformedArr = array();
foreach ($aa as $key => $value){
$transformedArr[] = array(
'customFieldId' => $key,
'value' => array($value)
);
}
$createContact->setCustomFieldValues($transformedArr);

Sort data array structure in php for Czech language

I am getting JSON in php from remote API and after that with usort i am sorting data arrays from a to z. But i need to sort it in Czech alphabet.
This is my current code:
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true )['data']['items'];
usort($data,function($a,$b) {return strnatcasecmp($a['city'],$b['city']);});
Can you help me?
Thanks
Since you did not provide the array structure I just assumed one.
$data = array(
'items' => array(
0 => array('city' => 'Froni'),
1 => array('city' => 'Frans'),
2 => array('city' => 'Frédéric')
),
);
usort($data['items'],
function($a,$b) {
$coll = collator_create( 'fr_FR' );
$aSortKey = collator_get_sort_key($coll, $a['city']);
$bSortKey = collator_get_sort_key($coll, $b['city']);
return $aSortKey >= $bSortKey;
}
);
var_dump($data['items']);
This takes advantage of the Collator Sort Key rather than comparing the strings itself and is used to sort the strings within your usort anonymous function. You will most likely have to change the parameters going in the usort function and its locale, though.

Array in functions Yii Framework

can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.

How can I simplify a nested php array?

I'm writing a php web application where I have a nested array which looks similar to the following:
$results = array(
array(
array(
'ID' => 1,
'Name' => 'Hi'
)
),
array(
array(
'ID' => 2,
'Name' => 'Hello'
)
),
array(
array(
'ID' => 3,
'Name' => 'Hey'
)
)
);
Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.
My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.
Here is the code I have so far:
public function filterArray($results) {
$outputArray = array();
foreach ($results as $key => $row) {
}
return $outputArray;
}
Would anyone be able to suggest the most effective way to achieve what I am after?
Thanks :)
Simply use call_user_func_array as
$array = call_user_func_array('array_merge', $results);
print_r($array);
Demo

Retrieve first key in multi-dimensional array using PHP

I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.

Categories