Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Let's say I have an associative array like below:
$myAssocArray = [
[ 'Name' => 'AWS_Bucket-Name1', 'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name2', 'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name3', 'Value' => 'Bucket data',...],
[ 'Name' => 'AWS_Bucket-Name4', 'Value' => 'Bucket data',...],
];
From this I want to create a simple associative array like below:
[ ['AWS_Bucket-Name1' => 'Bucket data'], ['AWS_Bucket-Name2' => 'Bucket data'], ...]
So I can take two approaches to resolve this:
(1) Use array_map function in php:
$destinationArray = array_map('myMapFunction', $myAssocArray);
function myMapFunction($entity): array {
if (is_array($entity) && isset($entity['Name'], $entity['Value'])) {
return [$entity['Name'] => $entity['Value']];
}
}
OR
(2) Using array_column and array_combine functions:
$keys = array_column($myAssocArray, 'Name');
$values = array_column($myAssocArray, 'Value');
$destinationArray = array_combine($keys, $values);
What will be more recommended approach and which will be more performant and efficient? OR is there even better solution available that does not need foreach loop?
I wouldn't look at the performance here because these operations are very small. I would focus more on the clean code side.
array_map() solution is harder to understand at the first look.
You don't need to use array_combine() and double invocation of array_column(). Instead you can pass third argument to array_column() which is
"index key"
The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.
The following code
array_column($myAssocArray, 'Value', 'Name')
prints the same output as desired.
Have in mind that PHP internally can notice and optimize a lot of things to improve performance. Obviously, it's better when developer does so, but sometimes you gain 1 μs of performance with the cost of clean code and headache of a developer maintaining that code.
Working fiddle
More info on php.net/array_column
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the following array:
$fields = ['field1', 'field2', 'field3'];
What I would like to do using an existing helper ('hopefully') is to convert those array string values into object key value pairs with an empty value.
This is the desired output:
$fields = (object) [
'field1' => '',
'field2' => '',
'field3' => '',
];
Is it possible to do that using a Laravel helper, so I don't have to use my own function?
You could try the following code to create a generic object.
$obj = new \stdClass();
foreach ($fields as $field) {
$obj->$field = '';
}
The reason this works is that it will iterate over each field, add set properties on the object, using the value of the array.
Note the ->$ symbol. This is because PHP will solve the $ into the value of the variable, then it will set that as the property after the arrow.
If you were to use an associative array, then you could take this a step further.
$fields = ['field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3'];
foreach ($fields as $field => $value) {
$obj->$field = $value;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an array that looks like this:
And I need to translate it into this:
Some things to know about the $startArray is that it is dynamic based on the amount of people submitted on a form. Each person always has just those three fields though (custom_12, custom_13, custom_14 aka fName, lName, email). So if there were 5 members, the 5th members fName would be the key custom_12-5 in the start array.
I've been looking around on stackoverflow for a question just like this and I was not able to find one. What would be the steps taken and possible array functions or anything else for creating the $endArray ?
There's actually a builtin function for this: https://www.php.net/manual/en/function.array-chunk.php
For example, array_chunk($startArray, 3) will give you the base for your new array, you'll just need to then iterate through it and rename the keys.
Alternatively, just iterate through the array yourself and add the values to a new array depending on the index of the current iteration.
Thanks to Charlie's advice, I came up with this.
$startArray = array(
'custom_12' => 'john',
'custom_13' => 'johny',
'custom_14' => 'john#johny.com',
'custom_12-2' => 'bob',
'custom_13-2' => 'bobby',
'custom_14-2' => 'bob#bobby.com',
'custom_12-3' => 'don',
'custom_13-3' => 'donny',
'custom_14-3' => 'don#donny.com'
);
$middleArray = array_chunk($startArray, 3);
$endArray = array_map(function($val) {
return array(
'fName' => $val[0],
'lName' => $val[1],
'email' => $val[2]
);
}, $middleArray);
echo "<pre>";
print_r($endArray);
echo "</pre>";
And the output is exactly what I wanted:
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an array with following elements:
$arr = array(
'nick' => "blabla",
'pass => "blabla2"'
);
I would like to convert it somehow to strings, the first string would be the value of nick - "blabla", the second string would be the value of pass - "blabla2"
Thank you.
If you want to convert elements of the array to separate string variables you can use extract function to import elements from an array to variables. For example:
$arr = array(
'nick' => "blabla",
'pass' => "blabla2"
);
extract($arr);
echo $nick, ' ', $pass;
$arr = [
'nick' => "blabla",
'pass' => "blabla2"
];
$string_one=$arr['nick'];
$string_two=$arr['pass'];
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am new at PHP and struggling with given problem.
I have to write a function winner_generator($parameter, $random) that would pick and show random name from given array:
<p><?php echo winner_generator(array(
array('name' => 'Bob'),
array('name' => 'Donald'),
array('name' => 'Peter'),
array('name' => 'Nick')
),rand()); ?></p>
Any ideas on how I should start solving this problem? Many thanks for all your help, looking forward.
So the idea is generating a random number between 0 and the length of the array - 1 (because the index of an array starts at 0). Then you pick the candidate at whatever number the random returns. As you want to echo the winner you need to select the 'name' key from the candidate array.
<?php
function winner_generator(array $candidates){
$rand = rand(0, sizeof($candidates)-1);
return($candidates[$rand]['name']);
}
echo winner_generator(array(
array('name' => 'Bob'),
array('name' => 'Donald'),
array('name' => 'Peter'),
array('name' => 'Nick')
));
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got an array for events on my site that looks like this:
array(
'title' => 'Name',
'link' => 'http://www.eventssite.com',
'image' => '_img/event_img.jpg',
'location' => 'Florida, US',
'year' => '2013',
'date' => 'Dec. 12-14',
'desc' => 'Description about the event.',
'dateid' => '1212013'
),
I'd like to sort the array before the foreach by the dateid so that they show in the proper Date order.
Additionally I'm trying to identify which one of the events is closest to the actual date, as I am using a carousel type system that needs to know which to display first.
I've researched usort and am not able to get it to go on my own, Thank you for any assistance on these!
Using this function: http://php.net/usort
An example would be something like:
<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
array(
'date' => '05/02/1988',
'name' => 'Jacob'
),
array(
'date' => '12/12/1968',
'name' => 'Sherry'
),
array(
'date' => '05/15/1978',
'name' => 'Dave'
)
);
//usort is used for non conventional sorting.
//which could help in this case
//NOTICE - we are not setting a variable here!
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');
//display the results
var_dump($array);
//function called by usort
function sortFunction($a,$b){
//turn the dates into integers to compare them
//
$strA = strtotime($a['date']);
$strB = strtotime($b['date']);
//don't worry about sorting if they are equal
if($strA == $strB){
return 0;
}
else{
//if a is smaller than b, the move it up by one.
return $strA < $strB ? -1 : 1;
}
}
?>
(in case youre interested, line 40 is called a Ternary)
edited for clarity