i'm a newbie in programming and in php too and i was wondering if anyone can help me with my array problem.
i have two set of array, example:
$name = array("peter","peter","joe");
$cars = array("ford", "gmc", "mercy");
and i would like to merge them into a multidimensional array like this
$merge = array(array($name[0], $cars[0]),array($name[1], $cars[1]),array($name[2], $cars[2]));
now, i would like keep the structure as above but i would like to do it with a native array function or foreach function.
i've tried array_merge and array_combine but it didn't turn out as i expected.
i've tried $arr3 = $name + $cars; but it didn't work too
does anyone can help me on what function should i use?
many thanks
~aji
array_map sounds like what you are looking for. See "Example #4 Creating an array of arrays"
An interesting use of this function is to construct an array of arrays, which can be easily performed by using NULL as the name of the callback function
$merged = array_map(NULL, $name, $cars);
$name = array("peter","peter","joe");
$cars = array("ford", 'gm$c', "mercy");
for($i=0;$i<count($name);$i++){
$array[$i]=array($name[$i],$cars[$i]);
}
print_r($array);
Related
I have an dynamic array that could for example look like this:
$arr = array(42, 30, 70, 10);
I have a function called CreateOrder and I want it to return an array like this
function createOrder($array)
{
/*
This function should return an array starting at 0,
while keeping the correct order, like this:
*/
$new_array = array(2, 1, 3, 0);
}
I have been trying and trying with foreach loops but I can't get my head around it.
Any help appreciated,
Nathan
If you don't mind the order of the original array being trashed in the process:
asort($arr);
$new_array = array_combine(array_keys($arr), range(0,count($arr)-1));
ksort($new_array);
Not so bad inside a function, because that uses a copy of the original array unless you pass by reference, so only the order of the locally-function-scoped copy gets trashed
Or even more simply:
asort($arr);
$new_array = array_keys($arr);
asort($new_array);
$newArr = array_keys($new_array);
Maybe the asort() function will fit your needs:
http://php.net/manual/de/function.asort.php
Don't forget to pass your array by reference, so this has to be called as is (without an assignment).
Clone the array.
Sort the cloned array in ascending order.
For each element in the original array search for key in sorted array, and insert the returned position in the new array.
return the position array.
Following code will help
function createOrder($array){
$cloneArray = asort($array);
$positionArray = [];
foreach($cloneArray as $element){
$positionArray[] = array_search($element,$array);
}
return $positionArray;
}
I need to tell array_merge_recursive what variables it needs to merge
I have the variable names that I need to use as strings, for example I have the following
$array1 = array('color'=>'blue', 'taste'=> 'sour', 'size'=>'big');
$array2 = array('color'=>'green', 'taste'=> 'sweet', 'size'=>'medium');
$array3 = array('color'=>'black', 'taste'=> 'sour', 'size'=>'small');
$array4 = array('color'=>'grey', 'taste'=> 'sweet', 'size'=>'big');
$allarrays = array_merge_recursive($array1, $array2, $array3, $array4);
This will work okay and merge my arrays, but I need to add a foreach to get the list of the arrays that I need and to set the array's that are going to the merged.
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $data;
}
$allarrays = array_merge_recursive($toBeMerged);
This doesn't work as it looks like I cannot use an array as the arguments for the array_merge_recursive.
I was thinking maybe I can use the list function for this but I haven't used it yet, what can I use to get what I need?
Two elements to handling this the way you want to:
Variable variables to build the to be merged array
$arraysThatINeedToAddToTheMerge = array('array2', 'array4');
$toBeMerged = [];
foreach ($arraysThatINeedToAddToTheMerge as $data){
$toBeMerged[] = $$data;
}
This will build an array of arrays, rather than simply an array of the names of your variables;
And (a modern PHP solution) then unpack the array arguments to be merged when calling array_merge_recursive
$allarrays = array_merge_recursive(...$toBeMerged);
or use call_user_func_array() for older versions of PHP
$allarrays = call_user_func_array('array_merge_recursive', $toBeMerged);
I need to remove a element from an associative array with an string structure.
Example:
$array = array(
"one"=>array("Hello", "world"),
"two"=>"Hi"
)
I want to create a function that removes the elements like this:
function removeElement($p) {
// With the information provided in $p something like this should happen
// unset($array["one"]["hello"])
}
removeElement("one.hello");
Your base array is associative, the inner array (key one) is not, its a indexed array, which you can not access via ["hello"] but rather [0].
You can remove the hello value by using the unset function, but the indexes will stay as they are:
$array = ['Hello', 'World']; // array(0: Hello, 1: World)
unset($array[0]); // Array is now array(1: World)
If you wish to keep unset and keep the array indexes in order, you can fetch the values using the array_values function after unset:
unset($array[0]);
$array = array_values($array); // array(0: World)
Or you could use array_splice.
When it comes to using a string as key for multidimensional array with a dot-separator I'd recommend taking a look at laravels Arr::forget method which does pretty much exactly what you are asking about.
This would be a static solution to your question, in any case, you need to use explode.
function removeElement($p, $array) {
$_p = explode('.', $p);
return unset($array[$_p[0]][$_p[1]]);
}
But bear in mind, this doesn't work if you have more in $p (like: foo.bar.quux)
PHP has plenty of useful functions and Im wondering if Im overlooking one that has already been built.
Lets say you have an array such as:
$first_array = array("Name"=>"Angela", "Age"=>24);
and you wanted to grab the keys from the first array to create a second array (which could then be pushed into a third array). So you need to create:
$second_array = array("Name", "Age");
Is there a way to achieve this result without this loop?:
foreach($first_array as $k=>$v){
array_push($second_array, $k);
}
This should do it:
array_keys($first_array);
Use array_keys($first_array) to get the array of all the keys in the $first_array
I like to learn how to combine two associative array which has same keys but different values like how we do in jQuery with var options = $.extend(defaults, options);
$first = array("name"=>"John","last_name"=>"McDonald","City"=>"World"); //default values
$second = array("name"=>"Michael","last_name"=>"Jackson"); //user provided
$result = combine($first,$second);
//output array("name"=>"Michael","last_name"=>"Jackson","City"=>"World");
I am looking for something built-in instead of writing a entire new function to provide this feature. Of course if you have something neat, just let me know.
Thanks...
$result = array_merge($first, $second);
As long as you're dealing with string keys, array_merge does exactly what you want. The two arrays are combined, and where the two have the same keys, the values from $second overwrite the values from $first.
array_merge()
I think array_merge() or array_combine() are the functions you are searching for.
you can iterate on second array and setting each element in first array
I think array_merge() or array_combine() are the functions you are looking for
array_merge() may used to merge the two array which are further called.
and the array_combine() the keys of a array with the values of a another array.
if you know exactly which key you want override you can simply do that like this
$first['name']="jastin";
otherwise you have to use array_merge
I've never found a built-in function for this (simple) need, so I developed a custom function in order to override a $default array with an $override array:
function array_override( $default, $override )
{
foreach( $default as $k=>$v )
{
if( isset( $override[$k] ) ) $default[$k] = $override[$k];
}
return $default;
}
As you can see, values in $default are overridden only if are set on the $override array; otherwise the $default value remain on the returned array.