I am stuck on this i have multiple associative array and i want to convert in to one:-
Here is the array:-
Array
(
[0] => Array
(
[0] => Women
)
[1] => Array
(
[0] => children
[1] => smile
)
[2] => Array
(
[0] => Abstract
)
[3] => Array
(
[0] => Lion
[1] => Cheetah
)
)
I want output something like this:-
Array
(
[0] => Women
[1] => children
[2] => smile
[3] => Abstract
[4] => Lion
[5] => Cheetah
)
Here i have tried so far:-
$getKeywords = DB::table('contributor_images')->select('keywords')->get();
$getKeywords = json_decode(json_encode($getKeywords),true);
foreach($getKeywords as $keyword){
$AllKeywords[] = $keyword['keywords'];
}
foreach ($AllKeywords as $key => $ExplodeKeywords) {
$searchkeywords[] = explode(',',$ExplodeKeywords);
}
echo "<pre>"; print_r($searchkeywords); die;
I am using laravel framework of php. THANKS IN ADVANCE :)
You can use Laravel helper function array_flatten for this:
$array = [
0 => [
0 => 'Women',
],
1 => [
0 => 'children',
1 => 'smile',
],
2 => [
0 => 'Abstract',
],
3 => [
0 => 'Lion',
1 => 'Cheetah',
],
];
$result = array_flatten($array);
var_dump($result);
Output:
array (size=6)
0 => string 'Women' (length=5)
1 => string 'children' (length=8)
2 => string 'smile' (length=5)
3 => string 'Abstract' (length=8)
4 => string 'Lion' (length=4)
5 => string 'Cheetah' (length=7)
Try this:
foreach ($old as $data) {
foreach ($data as $value) {
$new[] = $value;
}
}
print_r($new);
}
In first foreach you are getting array inside array and in second foreach you will get the value. Insert these values in new array to get desired result. Use print_r to see the result
Simply you can use : call_user_func_array
<?php
$array = array (
0 =>
array (
0 => 'Women',
),
1 =>
array (
0 => 'children',
1 => 'smile',
),
2 =>
array (
0 => 'Abstract',
),
3 =>
array (
0 => 'Lion',
1 => 'Cheetah',
),
);
$result = call_user_func_array('array_merge', $array);
print_r($result);
?>
Output :
Array
(
[0] => Women
[1] => children
[2] => smile
[3] => Abstract
[4] => Lion
[5] => Cheetah
)
Check here : https://eval.in/829111
Ref : http://php.net/manual/en/function.call-user-func-array.php
Since Laravel 5.7 the syntax is Arr::flatten($array) so that now it looks like
use Illuminate\Support\Arr;
$array = [
0 => [
0 => "Women"
],
1 => [
0 => 'children',
1 => 'smile'
],
2 => [
0 => 'Abstract'
],
3 => [
0 => 'Lion',
1 => 'Cheetah'
]
];
Arr::flatten($array);
Output :
array:6 [
0 => "Women"
1 => "children"
2 => "smile"
3 => "Abstract"
4 => "Lion"
5 => "Cheetah"
]
Docs be here
Related
I have 2 arrays one contains just a list of email address and the other contains emails and names.
The list of emails in array1 are stored in a database and the other array is a list of new and current users.
I have tried using array_diff however this only seems to work if I specify in my loop that I just want emails.
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$array2emails = array();
foreach ($array2 as $item) {
$array2emails[] = $item[1];
}
$result = array_diff($array2emails, $array1);
$results gives me
Array
(
[1] => james#jameshouse.com
[2] => marvin#marvinshouse.com
[3] => jane#janeshouse.com
)
however I need to get this:
Array
(
[1] => array(
[0] => james
[1] => james#jameshouse.com
)
[2] => array(
[0] => marvin
[1] => marvin#marvinshouse.com
)
[3] => array(
[0] => jane
[1] => jane#janeshouse.com
)
)
Any help would be much appreciated. Thanks
Since the array returned by array_diff has the same keys as the original array, you can use that to get the elements of the original array back, with array_intersect_key.
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$array2emails = array_column($array2, 1);
$keys = array_diff($array2emails, $array1);
$result = array_intersect_key($array2, $keys);
print_r($result);
Result:
Array
(
[1] => Array
(
[0] => james
[1] => james#jameshouse.com
)
[2] => Array
(
[0] => marvin
[1] => marvin#marvinshouse.com
)
[3] => Array
(
[0] => jane
[1] => jane#janeshouse.com
)
)
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$diffs = array();
foreach ($array2 as $item) {
if (!in_array($item[1], $array1)) {
$diffs[] = $item;
}
}
Since you are using a foreach loop why not create the array there?
As long as the arrays are not to long this will word nicely. I even took the original key into the new array. So you will be able to do other comparison methods to it.
$array1 = [
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
];
$array2 = [
0 => [
0 => 'tom',
1 => 'tom#tomshouse.com'
],
1 => [
0 => 'james',
1 => 'james#jameshouse.com'
],
2 => [
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
],
3 => [
0 => 'jane',
1 => 'jane#janeshouse.com'
],
];
$arrayExits = [];
foreach ($array2 as $key => $item) {
if(in_array($item[1], $array1)) {
$arrayExits[$key] = $item;
}
}
print_r($arrayExits);
Use array_filter function.
function filterEmail($value, $key){
global $array1;
return !in_array($value[1], $array1);
}
$emailDiff = array_filter($array2, 'filterEmail' , ARRAY_FILTER_USE_BOTH );
print_r($emailDiff );
This question already has answers here:
How to group subarrays by a column value?
(20 answers)
Closed 2 years ago.
Is there function that works similar to array_column for multidimensional arrays? Is there a function that translates the first array below to the second:
Array
(
[0] => Array
(
[foodType] => fruits
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[foodType] => fruits
[itemID] => 2
[itemName] => banana
)
[2] => Array
(
[foodType] => veggies
[itemID] => 3
[itemName] => carrot
)
[3] => Array
(
[foodType] => veggies
[itemID] => 4
[itemName] => broccoli
)
)
Resulting array:
Array
(
[fruits] => Array
(
[0] => Array
(
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[itemID] => 2
[itemName] => banana
)
)
[veggies] => Array
(
[0] => Array
(
[itemID] => 3
[itemName] => carrot
)
[1] => Array
(
[itemID] => 4
[itemName] => broccoli
)
)
)
No, there is not a function to get your expected output natively, though you can make your own functions, just use array_column to get the types/column, and then loop over your array, on match remove the item as to not duplicate iterations.
Something like:
<?php
$data = [
['foodType' => 'fruits', 'itemID' => 1, 'itemName' => 'apple'],
['foodType' => 'fruits', 'itemID' => 2, 'itemName' => 'banana'],
['foodType' => 'veggies', 'itemID' => 3, 'itemName' => 'carrot'],
['foodType' => 'veggies', 'itemID' => 4, 'itemName' => 'broccoli']
];
function array_column_multi ($array, $column) {
$types = array_unique(array_column($array, $column));
$return = [];
foreach ($types as $type) {
foreach ($array as $key => $value) {
if ($type === $value[$column]) {
unset($value[$column]);
$return[$type][] = $value;
unset($array[$key]);
}
}
}
return $return;
}
print_r(array_column_multi($data, 'foodType'));
https://3v4l.org/KQVeN
Result:
Array
(
[fruits] => Array
(
[0] => Array
(
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[itemID] => 2
[itemName] => banana
)
)
[veggies] => Array
(
[0] => Array
(
[itemID] => 3
[itemName] => carrot
)
[1] => Array
(
[itemID] => 4
[itemName] => broccoli
)
)
)
Oh I just noticed that you're aggregating them by ID. There's not a function for that, you're going to need to iterate over the input with a loop, and populate an output array with the data you want. Eg:
$output = [];
foreach($input_array as $item) {
$output[$item['id']][] = [
'itemID' => $item['itemID'],
'itemName' => $item['itemName']
];
}
Quite old question, but I hope it help someone. Unfortunately there's no native function yet but output is achievable using php's array_filter():
$foods = [
[
'foodType' => 'fruits',
'itemID' => 1,
'itemName' => 'apple',
],
[
'foodType' => 'fruits',
'itemID' => 2,
'itemName' => 'banana',
],
[
'foodType' => 'veggies',
'itemID' => 3,
'itemName' => 'carrot',
],
[
'foodType' => 'veggies',
'itemID' => 4,
'itemName' => 'broccoli',
]
];
$grouped_foods = [];
$groupByColumn = 'foodType';
array_filter($foods, function ($foodItem) use(&$grouped_foods, $groupByColumn) {
$grouped_foods[$foodItem[$groupByColumn]][] = array_filter($foodItem, function ($key) use($groupByColumn) {
return $key != $groupByColumn;
}, ARRAY_FILTER_USE_KEY);
});
echo "<pre>";
print_R($grouped_foods);
echo "</pre>";
see in action: https://3v4l.org/bbX5A
Disclaimer: for/foreach loops are significantly faster in performance than native array functions.
I prefer using the following solution.
Example
"allergens" => array:5 [
0 => array:2 [
"id" => "10"
"object" => array:1 [
"allergens" => "10"
]
]
1 => array:2 [
"id" => "11"
"object" => array:1 [
"allergens" => "11"
]
]
2 => array:2 [
"id" => "4"
"object" => array:1 [
"allergens" => "4"
]
]
]
Giving this example, if you would like an array containing only the value of allergens then use the following code.
Solution
$allergens = array_map( function ( $ar ) {
return $ar['allergens'];
}, array_column( $allergensArr, 'object' ) );
Result
array:5 [
0 => "10"
1 => "11"
2 => "4"
]
I am trying to change the following array to an almost flat array. So id 4 would be in the first level of the array, as would id 6 and 5, but still have their own index so I can tell which page is which. But with the same order as they have now. I presume that the solution would be some sort of recursive PHP function but I haven't a clue how to do this.
Array
(
[0] => Array
(
[id] => 2
[identifier] => External URL
[parent] => 0
[sortOrder] => 1
[depth] => 0
)
[1] => Array
(
[id] => 3
[identifier] => First Team
[parent] => 0
[sortOrder] => 2
[depth] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[identifier] => League tables
[parent] => 3
[sortOrder] => 0
[depth] => 1
[children] => Array
(
[0] => Array
(
[id] => 6
[identifier] => British and Irish Cup Tables
[parent] => 4
[sortOrder] => 24
[depth] => 2
)
[1] => Array
(
[id] => 5
[identifier] => Greene King IPA Championship
[parent] => 4
[sortOrder] => 25
[depth] => 2
)
)
)
)
)
[2] => Array
(
[id] => 1
[identifier] => Home
[parent] => 0
[sortOrder] => 25
[depth] => 0
)
)
<?php
$data = [
[
'id' => 1,
'name' => 'one',
'children' =>
[
[
'id' => 2,
'name' => 'two',
'children' =>
[
[
'id' => 4,
'name' => 'four'
]
]
],
[
'id' => 3,
'name' => 'three',
'children' =>
[
[
'id' => 5,
'name' => 'five'
]
]
]
]
],
[
'id' => 6,
'name' => 'six'
]
];
$stanley = [];
$flatten = function(array $data) use (&$flatten, &$stanley) {
foreach($data as $k => $v) {
if(isset($v['children'])) {
$flatten($v['children']);
unset($v['children']);
}
$stanley[] = $v;
}
};
$flatten($data);
var_export($stanley);
Output:
array (
0 =>
array (
'id' => 4,
'name' => 'four',
),
1 =>
array (
'id' => 2,
'name' => 'two',
),
2 =>
array (
'id' => 5,
'name' => 'five',
),
3 =>
array (
'id' => 3,
'name' => 'three',
),
4 =>
array (
'id' => 1,
'name' => 'one',
),
5 =>
array (
'id' => 6,
'name' => 'six',
),
)
I have found the solution! I built a recursive PHP function which utilised the depth index to track which level each of the items are while still keeping the array flat (ish).
function dropdownNavigationTree($array) {
$response = [];
foreach($array as $page) {
if (!is_array($page['children'])) {
$response[$page['id']] = ($page['depth'] > 0 ? str_repeat("-", $page['depth']).' ' : FALSE).$page['identifier'];
} else {
$response[$page['id']] = ($page['depth'] > 0 ? str_repeat("-", $page['depth']).' ' : FALSE).$page['identifier'];
$children = dropdownNavigationTree($page['children']);
$response = $response + $children;
}
}
return $response;
}
I'm stuck and I just need a pointer.
I have this string with special characters retrieved from db and i want to segment it to many strings or arrays and in the process i want to exchange those characters with "()".
|p| stands for parent. |c| child.
Example sentence is :
my beautiful car is awesome
*where my , beautiful and car have a parent-child relationship.
The pattern for it :
|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome
In case you need to see the original array:
Array
(
[0] => Array
(
[name] => |p|my
[parent_id] => 0
[child] => Array
(
[0] => Array
(
[name] => |c||p|beautiful
[parent_id] => 1
[child] => Array
(
[0] => Array
(
[name] => |c||c||p|car
[parent_id] => 2
)
)
)
)
)
[1] => Array
(
[name] => |p|is
[parent_id] => 0
)
[2] => Array
(
[name] => |p|awesome
[parent_id] => 0
)
)
The ultimate goal after segmenting and replacement is:
((My(beautiful(car)) (is)(awesome))
<?php
$items =
[
[
'name' => 'foo',
'children' =>
[
[
'name' => 'bar',
'children' =>
[
[
'name' => 'baz',
]
]
]
]
],
[
'name' => 'bat',
],
[
'name' => 'man',
]
];
function bracketize($array) {
$output = '';
foreach($array as $item) {
$output .= '(';
$output .= $item['name'];
if(isset($item['children']))
$output .= bracketize($item['children']);
$output .= ')';
}
return $output;
}
$output = '(' . bracketize($items) . ')';
print $output;
Output:
((foo(bar(baz)))(bat)(man))
Since you requested only a pointer I suggest to start with a regex to get an intermediate array:
$str = '|p|my|c||p|beautiful|c||c||p|car|p|is|p|awesome';
$res = preg_split('/((?:\|c\|)*\|p\|)/', $str, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_export($res);
/*
array (
0 => '|p|',
1 => 'my',
2 => '|c||p|',
3 => 'beautiful',
4 => '|c||c||p|',
5 => 'car',
6 => '|p|',
7 => 'is',
8 => '|p|',
9 => 'awesome',
)
*/
we have an array like this :
Array
(
[0] => Array
(
[value] => aaa
[parent_id] => 5
)
[1] => Array
(
[value] => bbb
[parent_id] => 3
)
[2] => Array
(
[value] => ccc
[parent_id] => 3
)
)
as you can see 2 index have same [parent_id] , we need convert this array to this
Array
(
[0] => Array
(
[parent_id] => 5
[sub] => Array(
[0] =>(
[value] => aaa
)
)
)
[1] => Array
(
[parent_id] => 3
[sub] => Array(
[0] =>(
[value] => bbb
)
[1] =>(
[value] => ccc
)
)
)
)
in php we used this functions :
foreach ($Array as $item) {
$item['subs'] = array();
$indexedItems[$item['parent_id']] = (object) $item;
}
for($i=0; $i<count($Array); $i++){
if($Array[$i]['parent_id'] == $Array[$i-1]['parent_id']){
$indexedItems[$item['parent_id']]->subs[]=$Array[$i]['value'];
}
}
but it doesnot works , can you help us to do that , please ?
If u realy want that complicated array you gave as example you have to track the parent_id.
This is how :
<?php
$foo = [
[
'value' => 'aaa',
'parent_id' => 900,
],
[
'value' => 'aaa',
'parent_id' => 813,
],
[
'value' => 'aaa',
'parent_id' => 900,
],
[
'value' => 'aaa',
'parent_id' => 813,
],
];
$indexed = [];
foreach($foo as $f) {
$index = getParentIndex($indexed, $f['parent_id']);
if ($index === null) {
$indexed[] = [
'parent_id' => $f['parent_id'],
'subs' => [
['value' => $f['value'] ],
],
];
}else{
$indexed[$index]['subs'][] = [ 'value' => $f['value'], ];
}
}
function getParentIndex($array, $parent_id) {
for($i=0;$i<count($array);$i++) {
if ($array[$i]['parent_id'] == $parent_id) return $i;
}
return null;
}
var_dump($indexed);
However, this looks a very complicated array to work with imho.
I would suggest the following snippet :
$indexed = [];
foreach($foo as $f) {
if (!isset($indexed[$f['parent_id']])) $indexed[$f['parent_id']] = [];
$indexed[$f['parent_id']][] = $f['value'];
}
var_dump($indexed);
This will output an array similar to :
array (size=2)
900 =>
array (size=2)
0 => string 'aaa' (length=3)
1 => string 'aaa' (length=3)
813 =>
array (size=2)
0 => string 'aaa' (length=3)
1 => string 'aaa' (length=3)