Merge complex array php - php

I have a site developed in php (codeigniter) and I want to merge some array with same structure.
This is the constructor of my array:
$first = array();
$first['hotel'] = array();
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array();
$second['room'] = array();
$second['amenities'] = array();
/*
Insert data into $second array
*/
After insert data I want to merge this array but the problem is that I have subarray inside it and I want to create a unique array like that:
$total = array();
$total['hotel'] = array();
$total['room'] = array();
$total['amenities'] = array();
This is the try to merge:
$total = array_merge((array)$first, (array)$second);
In this array I have only the $second array why?

Use the recursive version of array_merge called array_merge_recursive.

It seems like array_merge doesn't do what you think it does: "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one." Try this:
function merge_subarrays ($first, $second)
$result = array();
foreach (array_keys($first) as $key) {
$result[$key] = array_merge($first[$key], $second[$key]);
};
return $result;
};
Then call it as:
$total = merge_subarrays($first, $second);
and, if I've correctly understood your question, $total will contain the result you're looking for.

There is no standard way of doing it, you just have to do something like:
<?php
$first = array();
$first['hotel'] = array('hello');
$first['room'] = array();
$first['amenities'] = array();
/*
Insert data into $first array
*/
$second = array();
$second['hotel'] = array('world');
$second['room'] = array();
$second['amenities'] = array();
$merged = array();
foreach( $first as $key => $value )
{
$merged[$key] = array_merge( $value, $second[$key] );
}
print_r( $merged );

Related

Get first number in array list

I use laravel. And then when from submitted, it pass value as array.
My question is, how i can split the value? I want number before '-' and after '-'.
I want just like below:
and
My code just like below
$form = $request->all();
$emelto = $form['emelto'];
$split = explode('-', $emelto );
but it shows error
explode() expects parameter 2 to be string, array given
Please someone can help me.
Explode each individual string as you tried.
Insert each number in it's respective column index in result.
Snippet:
<?php
$emelto = [
'4-2',
'11-5'
];
$data = [];
foreach($emelto as $str){
foreach(explode('-',$str) as $index => $s){
$data[$index] = $data[$index] ?? [];// assuming your PHP version supports ??
$data[$index][] = $s;
}
}
print_r($data);
You can use
$array1 = array();
$array2 = array();
foreach($request->emelto as $val){
$dataArray = explode('-', $val);
$array1[] = $dataArray[0];
$array2[] = $dataArray[1];
}
$emelto is an array and you are passing it to explode. You have to pass it like $emelto[0].
You should update your code with the below one.
<?php
$form = $request->all();
$emelto = $form['emelto'];
$array1 = explode('-', $emelto[0] );
$array2 = explode('-', $emelto[1] );
$array3 = array();
array_push($array3, $array1[0]);
array_push($array3, $array2[0]);
$array4 = array();
array_push($array4, $array1[1]);
array_push($array4, $array2[2]);
?>

Transform a monodimensional PHP array into a multidimensional one

How would you transform a monodimensional array into a multidimensional array in PHP? Suppose you have something like this
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
And you want a function to transform it into
$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';
The same function should of course transform
$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';
into
$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';
I was thinking of using explode, then eval on the results, but eval always feels like cheating to me and I guess it would keep my code from running in HipHop.
The reason I want to do this is that I have to export lots of different tables from a database into XML files, and I already have a robust function that turns a multidimensional array into XML.
Like this:
function build(array &$trg, array $k,$key,$value) {
$p = &$trg;
while ( !empty($k) ) {
$nk = array_shift($k);
if ( !isset($p[$nk]) ) {
$p[$nk] = [];
}
$p = &$p[$nk];
}
$p[$key] = $value;
return $p;
}
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$out = [];
foreach ($array as $key => $value ) {
$path = explode('.',$key);
$last = array_pop($path);
build($out,$path,$last,$value);
}
print_r($out);
You were on the right track with explode, but there's no need to use eval. Once you've got the pieces of the keys available, you can loop over them and incrementally assign a pointer into a new array:
<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$result = [];
$target = null;
foreach ($array as $key => $value) {
// Start by targeting the base of our resulting array
$target =& $result;
// Break the keys apart into pieces
$keyParts = explode('.', $key);
// Assign new target based on indexing into the result array one "piece" at a time
while ($part = array_shift($keyParts)) {
$target =& $target[$part];
}
// Finally, assign the value to our target
$target = $value;
}
See https://eval.in/625627

How to dynamically traverse a global array without creating any copy of it?

What happen if it is a very big array? One would try to save memory. The next example makes copies of parts of the array, but it should be not necessary, since the array is a global variable.
function arrayTraverse($key) {
global $someArray;
$keys = func_get_args();
$arrayPart = $someArray;
foreach ($keys as $key) {
$arrayPart = $arrayCopy[$key];
}
$value = $arrayPart;
return $value;
}
Usage example:
$someArray = [];
$someArray['aKey'] = [];
$someArray['aKey']['someOtherKey'] = [];
$someArray['aKey']['someOtherKey'][5] = [];
$someArray['aKey']['someOtherKey'][5]['value'] = 'hello';
echo arrayTraverse('aKey', 'someOtherKey', 5, 'value'); // hello

PHP filter links

i have this array
$array = array(
"http://www.mywebsite.com/eternal_link_1",
"http://www.mywebsite.com/eternal_link_2/",
"http://www.mywebsite.com/eternal_link_1/#",
"http://subdomain1.mywebwite.com",
"http://subdomain2.mywebwite.com/eternal_link",
"http://www.external-link.com"
);
$eternal_links = array();
$subdomain_links = array();
$external_links = array();
how i can filter $array and add the values to the 3 arrays above?
You can use strpos to find the correct string.
foreach($array as $item){
if(strpos($item, 'external') == TRUE){
array_push($external_links, $item);
}
// and go on..
}

Creating array from string

I need to create array like that:
Array('firstkey' => Array('secondkey' => Array('nkey' => ...)))
From this:
firstkey.secondkey.nkey.(...)
$yourString = 'firstkey.secondkey.nkey';
// split the string into pieces
$pieces = explode('.', $yourString);
$result = array();
// $current is a reference to the array in which new elements should be added
$current = &$result;
foreach($pieces as $key){
// add an empty array to the current array
$current[ $key ] = array();
// descend into the new array
$current = &$current[ $key ];
}
//$result contains the array you want
My take on this:
<?php
$theString = "var1.var2.var3.var4";
$theArray = explode(".", $theString); // explode the string into an array, split by "."
$result = array();
$current = &$result; // $current is a reference to the array we want to put a new key into, shifting further up the tree every time we add an array.
while ($key = array_shift($theArray)){ // array_shift() removes the first element of the array, and assigns it to $key. The loop will stop as soon as there are no more items in $theArray.
$current[$key] = array(); // add the new key => value pair
$current = &$current[$key]; // set the reference point to the newly created array.
}
var_dump($result);
?>
With an array_push() in the while loop.
What do you want the value of the deepest key to be?
Try something like:
function dotToArray() {
$result = array();
$keys = explode(".", $str);
while (count($keys) > 0) {
$current = array_pop($keys);
$result = array($current=>$result);
}
return $result;
}

Categories