I've got this array
array:2 [
0 => array:2 [
"monday_open" => "10:00:00"
"monday_close" => "20:00:00"
]
1 => array:2 [
"tuesday_open" => "00:00:00"
"tuesday_close" => "00:00:00"
]
]
How can i combine them become:
array:4 [
"monday_open" => "10:00:00"
"monday_close" => "20:00:00"
"tuesday_open" => "00:00:00"
"tuesday_close" => "00:00:00"
]
I've tried using array_walk_recrusive but it doesn't return me with key name:
array_walk_recursive($array, function ($v) use (&$arrayFlat) {
$arrayFlat[] = $v;
});
I've tried this one too but got the same result as array_walk_recrusive:
iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0)
Result:
array:4 [
0 => "10:00:00"
1 => "20:00:00"
2 => "00:00:00"
3 => "00:00:00"
]
Is there any other way to keep the key value?
You can add key param to the closure of the array_walk_recursive like this
array_walk_recursive($array, function ($v, $k) use (&$arrayFlat) {
$arrayFlat[$k] = $v;
});
Try this
$source_array = array(array("monday_open"=>"10:00:00", "monday_close" => "20:00:00"), array("tuesday_open" => "00:00:00", "tuesday_close" => "00:00:00"));
$my_array = array();
foreach($source_array as $source){
foreach($source as $key=> $val){
$my_array[$key] = $val;
}
}
print_r($my_array);
Related
Am working on some set of PHP array. Am trying to loop through each of them and check
the array whose name is equal to Josw Acade. Am using a for loop but I get zero
after extracting the data. I want to store the data in an array.
Array
array:6 [
0 => array:4 [
"id" => 1
"name" => "Josw Acade"
"value" => "Unlimited"
"plan_type" => "Superior"
]
1 => array:4 [
"id" => 2
"name" => "Verbal"
"value" => "true"
"plan_type" => "Superior"
]
2 => array:4 [
"id" => 12
"name" => "Josw Acade"
"value" => "$1,500,00"
"plan_type" => "Classic"
]
3 => array:4 [
"id" => 13
"name" => "Leon"
"value" => "true"
"plan_type" => "Classic"
]
4 => array:4 [
"id" => 14
"name" => "One Time"
"value" => "true"
"plan_type" => "Classic"
]
5 => array:4 [
"id" => 15
"name" => "Deat"
"value" => "$25,000"
"plan_type" => "Classic"
]
6 => array:4 [
"id" => 23
"name" => "Josw Acade"
"value" => "$100,000"
"plan_type" => "Essential"
]
]
Logic
$Inst = [];
for($med = 0; $med < count($array); $med++){
if($med['name'] == "Josw Acade"){
$Inst = $med['value'];
}
}
dd($Inst);
Your variables is not corretly set in the for loop, you are setting $med = 0 and acessing $med as an array.
Use filter, that runs a condition on each element and returns the items that satisfy that condition.
array_filter($array, function ($item) {
return $item['name'] === 'Josw Acade';
});
In general you don't have to make old school arrays anymore, foreach does the same.
$results = [];
foreach($array as $item)
{
if ($item['name'] === 'Josw Acade') {
$results[] = $item['value'];
}
}
You can use array_filter with callback
$filtered = array_filter($array, function($v){ return $v['name'] == 'Josw Acade'})
print_r($filtered);
You are looping through array; so on each iteration to get values; you need to pass index value and you are missing that. You are using $med as index.
Here is code.
$Inst = [];
for($med = 0; $med < count($array); $med++){
if($array[$med]['name'] == "Josw Acade"){
$Inst[] = $array[$med]['value'];
}
}
there is many way to do this but according to me the best way to use array_filer()
array_filter($array, function ($item) {
return $item['name'] === 'Josw Acade';
});
I have the following array:
$arr = [
"elem-1" => [ "title" => "1", "desc" = > "" ],
"elem-2" => [ "title" => "2", "desc" = > "" ],
"elem-3" => [ "title" => "3", "desc" = > "" ],
"elem-4" => [ "title" => "4", "desc" = > "" ],
]
First I need to change the value from [ "title" => "1", "desc" = > "" ] to 1 (title's value).
I did this using array_walk:
array_walk($arr, function(&$value, $key) {
$value = $value["title"];
});
This will replace my value correctly. Our current array now is:
$arr = [
"elem-1" => "1",
"elem-2" => "2",
"elem-3" => "3",
"elem-4" => "4",
]
Now, I need to transform each element of this array into its own subarray. I have no idea on how to do this without a for loop. This is the desired result:
$arr = [
[ "elem-1" => "1" ],
[ "elem-2" => "2" ],
[ "elem-3" => "3" ],
[ "elem-4" => "4" ],
]
You can change your array_walk callback to produce that array.
array_walk($arr, function(&$value, $key) {
$value = [$key => $value["title"]];
});
Run the transformed array through array_values if you need to get rid of the string keys.
$arr = array_values($arr);
To offer an alternative solution you could achieve all of this with array_map
<?php
$arr = [
"elem-1" => [ "title" => "1", "desc" => "" ],
"elem-2" => [ "title" => "2", "desc" => "" ],
"elem-3" => [ "title" => "3", "desc" => "" ],
"elem-4" => [ "title" => "4", "desc" => "" ],
];
function convertToArray($key,$elem){
return [$key => $elem['title']];
}
$arr = array_map("convertToArray", array_keys($arr), $arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
outputs
Array
(
[0] => Array
(
[elem-1] => 1
)
[1] => Array
(
[elem-2] => 2
)
[2] => Array
(
[elem-3] => 3
)
[3] => Array
(
[elem-4] => 4
)
)
It doesn't make much sense to use array_walk() and modify by reference because the final result needs to have completely new keys on both levels. In other words, the output structure is completely different from the input and there are no salvageable/mutable parts. Mopping up the modified array with array_values() only adds to the time complexity cost.
array_map() has to bear a cost to time complexity too because array_keys() must be passed in as an additional parameter.
If you want to use array_walk(), use use() to modify the result array. This will allow you to enjoy the lowest possible time complexity.
More concise than array_walk() and cleaner to read, I would probably use a classic foreach() in my own project.
Codes: (Demo)
$result = [];
array_walk(
$arr,
function($row, $key) use(&$result) {
$result[] = [$key => $row['title']];
}
);
Or:
$result = [];
foreach ($arr as $key => $row) {
$result[] = [$key => $row['title']];
}
var_export($result);
You need to use array_map like
$new_arr= array_map(function($key,$val){
return [$key => $val['title']];},array_keys($arr),$arr);
I have:
array:2 [
0 => array:1 [
"FNAME" => "nullable|string"
]
1 => array:1 [
"LNAME" => "nullable|string"
]
]
And I try to get:
array:1 [
"key" => "value"
]
I try map it, but has problem
<?php
$array = [
[
"FNAME" => "nullable|string",
],
[
"LNAME" => "nullable|string",
]
];
$newArray = [];
foreach ($array as $item) {
foreach ($item as $key => $value) {
$newArray[$key] = $value;
}
}
print_r($newArray);
Will output:
Array
(
[FNAME] => nullable|string
[LNAME] => nullable|string
)
Two simple ways:
print_r(array_merge(...$arr));
// if `...` is not available (php < 5.6), then:
print_r(call_user_func_array('array_merge', $arr))
I have an array that looks like this
"name" => array:3 [
1 => "Hello"
4 => "Test"
21 => "Test2"
]
"runkm" => array:3 [
1 => "100.00"
4 => "1000.00"
21 => "2000.00"
]
"active" => array:3 [
1 => "1"
4 => "0"
21 => "0"
]
Can i somehow combine the matching keys with a PHP function so that the array would look like this instead
1 => array:3 [
name => "Hello"
runkm => "100.00"
active => "1"
]
4 => array:3 [
name => "Test"
runkm => "1000.00"
active => "0"
]
21 => array:3 [
name => "Test2"
runkm => "2000.00"
active => "0"
]
EDIT: Thanks for all the answers guys. What i was really looking for was a PHP built in function for this, which i probably should have been more clear about.
$newArr=array();
foreach($array1 as $key => $value){
$newArr[$key]=>array(
'name' =>$value[$key];
'runkm' =>$array2[$key];
'active'=>$array3[$key];
);
}
this is how you make a new array and then print the $newArr and check you get what you want or not? Good Luck!
<?php
$resultarr = array();
for($i=0;$i<count($sourcearr['name']);$i++) {
$resultarr[] = array('name'=>$sourcearr['name'][$i], 'runkm'=>$sourcearr['runkm'][$i], 'active'=>$sourcearr['active'][$i]);
}
This works well. And also, doesn't use hard coded keys.
<?php
$arr = [
"name" => [
1 => "Hello",
4 => "Test",
21 => "Test2"
],
"runkm" => [
1 => "100.00",
4 => "1000.00",
21 => "2000.00"
],
"active" => [
1 => "1",
4 => "0",
21 => "0"
]
];
// Pass the array to this function
function extractData($arr){
$newarr = array();
foreach ($arr as $key => $value) {
foreach($value as $k => $v) {
if(!isset($newarr[$k]))
$newarr[$k] = array();
$newarr[$k][$key] = $v;
}
}
return $newarr;
}
print_r(extractData($arr));
?>
I'm not sure if there's a function that does that in PHP but maybe you can try this
$arr1 = array(
"name" => array(
1 => "hello",
4 => "test",
21 => "test2",
),
"runKm" => array(
1 => "100",
4 => "200",
21 => "300",
),
"active" => array(
1 => "1",
4 => "0",
21 => "0",
),
);
// declare another that will hold the new structure of the array
$nArr = array();
foreach($arr1 as $key => $val) {
foreach($val as $sub_key => $sub_val) {
$nArr[$sub_key][$key] = $sub_val;
}
}
what this does is simply loop thru each array and its values and assign it to another array which is the $nArr. I hope it helps.
I have following task to do, if there is any chance I would appreciate some help to make it in as efficient way as possible. I need to compare values from array of objects (which comes from Laravel Query Builder join query) with array values.
Objects consist of database stored values:
0 => array:2 [
0 => {#912
+"addition_id": 1
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "0.00"
+"mode": 0
+"alias": "Breakfast"
}
1 => {#911
+"addition_id": 2
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "10.00"
+"mode": 1
+"alias": "Dinner"
}
while array includes new data, being processed by my method.
0 => array:3 [
0 => array:6 [
"id" => 1
"alias" => "Breakfast"
"price" => "0.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:03"
"updated_at" => "2015-09-12 21:25:03"
]
1 => array:6 [
"id" => 2
"alias" => "Dinner"
"price" => "10.00"
"mode" => 1
"created_at" => "2015-09-12 21:25:18"
"updated_at" => "2015-09-12 21:25:18"
]
2 => array:6 [
"id" => 3
"alias" => "Sauna Access"
"price" => "50.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:35"
"updated_at" => "2015-09-12 21:25:35"
]
]
Now, what I need to do is to find out what position of the array was not in the object (compare id with addition_id) and return it.
Is there any way to do it without two nested foreach loops? I think it can be done somehow smart with array_filter, but I'm not really sure how to write efficient callback (beginner here).
The only way I could get around this was:
private function compareAdditions(array $old,array $new)
{
$difference = $new;
foreach($new as $key => $value) {
foreach($old as $oldEntry) {
if($oldEntry->addition_id == $value['id']) {
unset($difference[$key]);
}
}
}
return $difference;
}
But I would really like to make it without two foreach loops. Help will be very appreciated :)
This might be overkill but it uses a function i write in every project, precisely for these kind of situations :
function additionals($original, $additions) {
$nonExisiting = [];
//convert all the objects in arrays
$additions = json_decode(json_encode($additions), true);
//create an index
$index = hashtable2list($original, 'id');
for(reset($additions); current($additions); next($additions)) {
$pos = array_search(current($additions)['addition_id'], $index);
if($pos !== false) {
//We could replace the originals with the additions in the same loop and save resources
//$original[$pos] = current($additions);
} else {
$nonExisiting[] = current($additions);
}
}
return $nonExisiting;
}
function hashtable2list( $hashtable, $key ){
$array = [];
foreach($hashtable as $entry) {
if( is_array($entry) && isset($entry[$key])) {
$array[] = $entry[$key];
} elseif( is_object($entry) && isset($entry->$key) ) {
$array[] = $entry->$key;
} else {
$array[] = null;
}
}
return $array;
}