Array within array as single associative array - php

I am having array within array values as below.
Array
(
[0] => Array
(
[0] => Array
(
[Floor] => Floor-1
)
[1] => Array
(
[Flat] => Flat A2
)
[2] => Array
(
[Area] => Balcony,
)
)
)
I need to make it as single associative array as below.
Array
(
[0] => Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
)
How can i do this ?

This example should help you.
<?php
$arr = array(
array(
'floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
Output will be
Array
(
[floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
Here we have created an empty array called as $final_array we will append this array by using foreach loop.
Remember, if you have a same array key then the last value will overwrite like below.
<?php
$arr = array(
array(
'floor'=>'Floor-1',
'floor'=>'Floor-2',
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
array(
'Area'=>'Balcony2,'
),
);
$final_array = array();
foreach ($arr as $arr1) {
foreach ($arr1 as $key => $value) {
$final_array[$key] = $value;
}
}
?>
Now, output will be
Array
(
[floor] => Floor-2
[Flat] => Flat A2
[Area] => Balcony2,
)

<?php
$array = [
[
[
'foo' => 'big'
],
[
'bar' => 'fat'
],
[
'baz' => 'mamma'
]
]
];
$merged[0] = array_reduce($array[0], function($carry, $item) {
return array_merge((array) $carry, $item);
});
var_export($merged);
Output:
array (
0 =>
array (
'foo' => 'big',
'bar' => 'fat',
'baz' => 'mamma',
),
)

This single line code is enough to do this
$newArr = call_user_func_array('array_merge',$dataArr); ///where $dataArr is your array..
call_user_func_array will call a callback function with array of parameters and array_merge will merge all these parameters in single array read more about call_user_func_array() and array_merge()
Example code:
<?php
$dataArr = array(
array(
'Floor'=>'Floor-1'
),
array(
'Flat'=>'Flat A2'
),
array(
'Area'=>'Balcony,'
),
);
$newArr = call_user_func_array('array_merge',$dataArr);
echo "<pre>"; print_r($newArr);
?>
This will give you :
Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)

Related

how to explode array in php

i have data array, and this my array
Array
(
[0] => Array
(
[id] => 9,5
[item] => Item A, Item B
)
[1] => Array
(
[id] => 3
[item] => Item C
)
)
in array 0 there are two ID which I separated using a comma, I want to extract the data into a new array, how to solve this?
so the output is like this
Array
(
[0] => Array
(
[id] => 9
[item] => Item A
)
[1] => Array
(
[id] => 3
[item] => Item C
)
[2] => Array //new array
(
[id] => 5
[item] => Item B
)
)
this my code
$arr=array();
foreach($myarray as $val){
$arr[] = array(
'id' => $val['id'],
'item' => $val['item'],
);
}
echo '<pre>', print_r($arr);
$arr = [
array(
'id' => '9,5',
'item' => 'Item A, Item B'
),
array(
'id' => 3,
'item' => 'Item C'
)
];
$newArr = array_reduce($arr, function($tmp, $ele){
$arrIds = explode(',', $ele['id']);
$arrItems = explode(',', $ele['item']);
forEach($arrIds as $key => $arrId) {
$tmp[] = array('id' => $arrId, 'item' => $arrItems[$key]);
}
return $tmp;
});
The code down below should do the job. But I didn't understand why you didn't create those items seperately in the first place.
foreach ($arr as $i => $data) {
if (!str_contains($data['id'], ',')) continue;
$items = explode(',', $data['item']);
foreach(explode(',', $data['id']) as $i => $id) {
$new = ['id' => $ids[$i], 'item' => $items[$i]];
if ($i) $arr[] = $new;
else $arr[$i] = $new;
}
}

Array Push Inside an array

I want to push another array inside array.
This is my array. I want to push another array on textTabs .
Array
(
[recipients] => Array
(
[signers] => Array
(
[0] => Array
(
[email] => rm#gmail.com
[tabs] => Array
(
[checkboxTabs] => Array
(
[0] => Array
(
[tabLabel] => sampleCheckbox
)
)
[textTabs] => Array
(
[0] => Array
(
[tabLabel] => CompanyName
[value] => Qwerty
)
[1] => Array
(
[tabLabel] => TradingName
[value] => Qwerty
)
[2] => Array
(
[tabLabel] => ContactName
[value] => RM
)
)
)
)
)
)
)
This is my array that i want to add:
$array2 = array(
"tabLabel"=>"MonthlyTotal",
"value"=>$monthlytotal
);
And this is my php code:
$data = array_push($array1['recipients']['signers']['0']['tabs']['textTabs'], $array2);
But I was not able to push it. Thank you for your help.
No need of assignment of array_push() to $data,as child-array pushed to initial array itself. Just do:
array_push($array1['recipients']['signers']['0']['tabs']['textTabs'], $array2);
print_r($array1);
Output:- https://3v4l.org/sntUP
I always prefer doing assignment like below:
$array1['recipients']['signers']['0']['tabs']['textTabs'][] = $array2;
Output:-https://3v4l.org/nHHUB
If you do love a portable way to do add an array or any other values to any key, you may do it using recursive function. Let's see an example below:
<?php
$old_array = [
'one' => 'value for one',
'two' => 'value for two',
'three' => [
'four' => 'value for four',
'five' => 'value for five',
'six' => [
'seven' => 'value for seven',
'eight' => 'value for eight',
],
],
];
function addArrayToKey($array, $callback){
$result = [];
foreach($array as $key => $value){
if(is_array($value)) {
$result[$key] = addArrayToKey($value, $callback);
} else {
$result[$key] = $callback($key, $value);
}
}
return $result;
}
function callback($key, $value) {
if('seven' == $key) {
return ['one', 'two', 'three' => ['four', 'five']];
}
return $value;
}
echo '<pre>';
print_r(addArrayToKey($old_array, 'callback'));

shift multidimentional array to single array

I want to remove key 0 from parent array and set child array as parent.
Here I will get single value so one array is ok for me.
My current array looks like this
Array
(
[0] => Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
)
I want it like below. expected result
Array
(
[id] => 3
[api_key] => acount266
[auth_domain] => Tester26
[database_url] => vcc.test.acc+27#gmail.com
[project_id] => 12345
[storage_bucket] =>
[secret_key_path] =>
[fcm_server_key] => 1
[messaging_sender_id] => 0
[key_phrase] =>
[disable] => 0
[created] =>
[updated] =>
)
For this I tried like below but no success.
$new = array();
foreach ($data as $v){
$new = array_merge($new , array_values($v)) ;
}
but in my code it's removed key e.g id,api_key, etc....
I need key name also in my new array. please suggest
Remove the array_values
Solution
<?php
$test = array(
array
(
'id' => 3,
'api_key' => 'acount266'
)
);
$new = array();
foreach($test as $v){
$new = array_merge($new, $v);
}
var_dump($new);
Result
array(2) {
["id"]=>
int(3)
["api_key"]=>
string(9) "acount266"
}
According to documentation of PHP as mentioned
reset() function returns the value of the first array element, or
FALSE if the array is empty.
$array = array(
array(
'id' => 3,
'api_key' => 'acount266',
'auth_domain' => 'Tester26',
'database_url' => 'vcc.test.acc+27#gmail.com',
'project_id' => '12345',
'storage_bucket' => '',
'secret_key_path' => '',
'fcm_server_key' => 1,
'messaging_sender_id' => 0,
'key_phrase' => '',
'disable' => 0,
'created' => '',
'updated' => ''
)
);
print_r(reset($test));
I tried this:
$arr = array();
foreach ($examples as $example) {
foreach ($example as $e) {
array_push($arr, $e);
}
}
Don't overcomplicate this, reassigning the first element to the parent array is quick and easy:
<?php
$array =
array (
0 =>
array (
'first' => 'Michael',
'last' => 'Thompson'
)
);
$array = $array[0];
var_export($array);
Output:
array (
'first' => 'Michael',
'last' => 'Thompson',
)
Or:
$array = array_shift($array);

php array match within a two dimensional array

for example, I have a array:
$objects = ['car', 'cat', 'dog', 'Peter'];
and another:
$types = [
'man' => ['Peter', 'John','...'],
'animal' => ['pig', 'cat', 'dog', '...'],
'vehicle' => ['bus', 'car', '...']
];
and my goal is get an array like:
$result = [
'man' => ['Peter'],
'animal' => ['cat', 'dog'],
'vehicle' => ['car']
]
what is the most efficient way to search within an array, in my current work, I use two foreach loop to search but figured it's too slow, I have about thousands of elements in my array.
Use array_intersect:
foreach ($types as $key => $type) {
$result[$key] = array_intersect($type, $objects);
}
$objects = ['car', 'cat', 'dog', 'Peter'];
$types = [
'man' => ['Peter', 'John'],
'animal' => ['pig', 'cat', 'dog'],
'vehicle' => ['bus', 'car']
];
foreach ($types as $key => $type) {
$result[$key] = array_intersect($type, $objects);
}
echo '<pre>';
print_r($result);
Array
(
[man] => Array
(
[0] => Peter
)
[animal] => Array
(
[1] => cat
[2] => dog
)
[vehicle] => Array
(
[1] => car
)
)

php create new array adding distinct values from existing one

Suppose i have 2 arrays:
$array1 =( [0] => Array ( [user] => 'aaa' [count] => '123' )
[1] => Array ( [user] => 'bbb' [count] => '456' )
[2] => Array ( [user] => 'ccc' [count] => '789' ) );
$array2= ( [0] => aaa)
[1] => ccc );
I would like to search values from second array in first array and create the third array that will contain all elements from first array, like this:
$array3 =( [0] => Array ( [user] => 'aaa' [count] => '123' )
[1] => Array ( [user] => 'ccc' [count] => '789' ) );
Please help. Thank you in advance
(sorry for bad english)
$array1 = array(
array( 'user' => 'aaa', 'count' => 123 ),
array( 'user' => 'bbb', 'count' => 456 ),
array( 'user' => 'ccc', 'count' => 789 ),
);
$array2 = array('aaa', 'ccc');
var_dump(array_filter($array1, function($el) use($array2) {
return in_array($el['user'], $array2);
}));
It preserves keys, you can reset them if needed. Or with foreach loop
$out = array();
foreach($array1 as $el)
{
if (in_array($el['user'], $array2))
$out[] = $el;
}
var_dump($out);
Can try using foreach(). Example here...
$array3 = array();
foreach($array2 as $search){
foreach($array1 as $val){
if($search == $val['user']){
$array3[] = $val;
}
}
}
print_r($array3);

Categories