PHP : merge multi arrays in sections - php

I load data from .xlsx sheet
And i convert it to two arrays
The first is the header columns
The second is the data columns
I did this
$c = array_combine($headers, $data);
when i print $c
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[f-name] => Array
(
[0] => Mohammed
[1] => Ziad
)
[s-name] => Array
(
[0] => Amer
[1] => Mohammed
)
[t-name] => Array
(
[0] => Hendy
[1] => Shokry
)
[cid] => Array
(
[0] => 89
[1] => 55
)
)
i want to make the result like that
array(
[0] => Array(
[id] => 0
[f-name] => mohammed
[s-name] => amer
[t-name] => hendy
[cid] => 89
)
[1] => Array(
[id] => 1
[f-name] => ziad
[s-name] => mohammed
[t-name] => shokry
[cid] => 55
)
)

try this:
$data = array(
'id' => array
(
0 => 1,
1 => 2
),
'f-name' => array
(
0 => 'Mohammed',
1 => 'Ziad'
),
's-name' => array
(
0 => 'Amer',
1 => 'Mohammed'
),
't-name' => array
(
0 => 'Hendy',
1 => 'Shokry'
),
'cid' => array
(
0 => 89,
1 => 55
)
);
//
$result = array();
foreach($data as $k=>$v){
for($i=0;$i<count($data['id']);$i++){
//$v[$i] = ($k!='id') ?: $i;// uncomment for reset id from 0
$result[$i][$k] = $v[$i];
}
}
var_dump($result);
result:
array (size=2)
0 =>
array (size=5)
'id' => int 1
'f-name' => string 'Mohammed' (length=8)
's-name' => string 'Amer' (length=4)
't-name' => string 'Hendy' (length=5)
'cid' => int 89
1 =>
array (size=5)
'id' => int 2
'f-name' => string 'Ziad' (length=4)
's-name' => string 'Mohammed' (length=8)
't-name' => string 'Shokry' (length=6)
'cid' => int 55

Try something like this:
for ($index = 0; &index < 2; ++$index)
{
thing['id'] = $index;
thing['f-name'] = $c['f-name'];
thing['l-name'] = $c['s-name'];
thing['t-name'] = $c['t-name'];
thing['cid'] = $c['cid'];
$newArra y[$index] = thing;
}

I like to include "fancy" array functions like array_walk and array_map whenever I have the chance:
Initialize your data
$data = [
'id' => [
0 => 1,
1 => 2
],
'f-name' => [
0 => 'Mohammed',
1 => 'Ziad'
],
's-name' => [
0 => 'Amer',
1 => 'Mohammed'
],
't-name' => [
0 => 'Hendy',
1 => 'Shokry'
],
'cid' => [
0 => 89,
1 => 55
]
];
Transform the data
$result = [];
array_walk($data['id'],
function($f, $i) use ($data, &$result){
$result[$i] = array_map(function($e) use ($i){
return $e[$i];
}, $data);
}
);
Output the result
var_dump($result);
array(2) {
[0]=>
array(5) {
["id"]=>
int(1)
["f-name"]=>
string(8) "Mohammed"
["s-name"]=>
string(4) "Amer"
["t-name"]=>
string(5) "Hendy"
["cid"]=>
int(89)
}
[1]=>
array(5) {
["id"]=>
int(2)
["f-name"]=>
string(4) "Ziad"
["s-name"]=>
string(8) "Mohammed"
["t-name"]=>
string(6) "Shokry"
["cid"]=>
int(55)
}
}

Related

How to merge array on behalf of a key value

I have an array
{
Array
(
[0] => Array
(
[filterType] => checkbox
[sfid] => a1d1I000000jrmwQAA
[name] => Publication Year
[specValues] => Array
(
[count] => 3
[value] => 1953
)
)
[1] => Array
(
[filterType] => checkbox
[sfid] => a1d1I000000jrmwQAA
[name] => Publication Year
[specValues] => Array
(
[count] => 1
[value] => 1954
)
)
)
}
But I want to merge array if sfid is same i.e i want result
{
Array
(
[0] => Array
(
[filterType] => checkbox
[sfid] => a1d1I000000jrmwQAA
[name] => Publication Year
[specValues] => Array(
[0] =>array(
[count] => 3
[value] => 1953
)
[1] =>array(
[count] => 1
[value] => 1954
)
)
)
)
}
You just need to iterate your array and add the row to the output if it is not in there already (you can use sfid as keys) and add specValues to the correct row.
<?php
$input = [
[
'filterType' => 'checkbox',
'sfid' => 'a1d1I000000jrmwQAA',
'name' => 'Publication Year',
'specValues' => [
'count' => 3,
'value' => 1953,
],
],
[
'filterType' => 'checkbox',
'sfid' => 'a1d1I000000jrmwQAA',
'name' => 'Publication Year',
'specValues' => [
'count' => 1,
'value' => 1954,
],
],
];
$data = [];
foreach ($input as $row) {
if (!isset($data[$row['sfid']])) {
$data[$row['sfid']] = [
'filterType' => $row['filterType'],
'sfid' => $row['sfid'],
'name' => $row['name'],
'specValues' => [],
];
}
$data[$row['sfid']]['specValues'][] = $row['specValues'];
}
var_dump(array_values($data));
Output:
array(1) {
[0]=>
array(4) {
["filterType"]=>
string(8) "checkbox"
["sfid"]=>
string(18) "a1d1I000000jrmwQAA"
["name"]=>
string(16) "Publication Year"
["specValues"]=>
array(2) {
[0]=>
array(2) {
["count"]=>
int(3)
["value"]=>
int(1953)
}
[1]=>
array(2) {
["count"]=>
int(1)
["value"]=>
int(1954)
}
}
}
}
I assume that if sfid is the same, then also filterType and name is the same.

How to sort multidimensional array in PHP

I have tried almost all suggestions online, and I really can't figure out how to sort this SESSION array.
I want it sorted by "itemname"..
I have and want this output, but I need the itemname to determine which item array come first.
Array
(
[person] => Array
(
[namex] => Array
(
[itema] => Array
(
[itemid] => 43
[itemname] => def
)
[itemc] => Array
(
[itemid] => 33
[itemname] => abc
)
[itemg] => Array
(
[itemid] => 29
[itemname] => ghi
)
)
[namey] => Array
(
[itemj] => Array
(
[itemid] => 12
[itemname] => abc
)
[iteme] => Array
(
[itemid] => 44
[itemname] => jkl
)
[itemr] => Array
(
[itemid] => 20
[itemname] => rst
)
)
)
)
So, "person" stays the same, but name, item, itemid and itemname is always different.
Can anyone help me sort this by itemname?
I need the array to be like this, so can't change it up.
Also.. I need to access it later in a foreach, so I can print out the items.
As pointed out in the comments to the question the desired output is not really defined. You'd have to give a specific definition of the output, without that we have to assume what you probably are looking for:
<?php
$data = [
"person" => [
"namex" => [
"itema" => [
"itemid" => 43,
"itemname" => "def"
],
"itemc" => [
"itemid" => 33,
"itemname" => "abc"
],
"itemg" => [
"itemid" => 29,
"itemname" => "ghi"
]
],
"namey" => [
"itemj" => [
"itemid" => 12,
"itemname" => "abc"
],
"iteme" => [
"itemid" => 44,
"itemname" => "jkl"
],
"itemr" => [
"itemid" => 20,
"itemname" => "rst"
]
]
]
];
foreach ($data["person"] as $personName => &$person) {
uasort($person, function($a, $b) {
return $a["itemname"] > $b["itemname"];
});
}
print_r($data);
The obvious output is:
Array
(
[person] => Array
(
[namex] => Array
(
[itemc] => Array
(
[itemid] => 33
[itemname] => abc
)
[itema] => Array
(
[itemid] => 43
[itemname] => def
)
[itemg] => Array
(
[itemid] => 29
[itemname] => ghi
)
)
[namey] => Array
(
[itemj] => Array
(
[itemid] => 12
[itemname] => abc
)
[iteme] => Array
(
[itemid] => 44
[itemname] => jkl
)
[itemr] => Array
(
[itemid] => 20
[itemname] => rst
)
)
)
)
Assuming the input from the example is represented via array as:
<?php
$array = [
'person' => [
'namex' => [
'itema' => [
'itemid' => 43,
'itemname' => 'def'
],
'itemb' => [
'itemid' => 33,
'itemname' => 'abc'
],
'itemc' => [
'itemid' => 29,
'itemname' => 'ghi'
],
],
'namey' => [
'itema' => [
'itemid' => 12,
'itemname' => 'abc'
],
'itemb' => [
'itemid' => 44,
'itemname' => 'jkl'
],
'itemc' => [
'itemid' => 20,
'itemname' => 'rst'
],
],
]
];
You could do use array_multisort in a loop:
$ids = [];
foreach($array as $key => $value) {
foreach ($value as $newKey => $value2) {
$ids[$newKey] = array_column($value2, 'itemname');
array_multisort($ids[$newKey], SORT_NATURAL, $array[$key][$newKey]);
}
}
This will output
array(1) {
'person' =>
array(2) {
'namex' =>
array(3) {
'itemb' =>
array(2) {
'itemid' =>
int(33)
'itemname' =>
string(3) "abc"
}
'itema' =>
array(2) {
'itemid' =>
int(43)
'itemname' =>
string(3) "def"
}
'itemc' =>
array(2) {
'itemid' =>
int(29)
'itemname' =>
string(3) "ghi"
}
}
'namey' =>
array(3) {
'itema' =>
array(2) {
'itemid' =>
int(12)
'itemname' =>
string(3) "abc"
}
'itemb' =>
array(2) {
'itemid' =>
int(44)
'itemname' =>
string(3) "jkl"
}
'itemc' =>
array(2) {
'itemid' =>
int(20)
'itemname' =>
string(3) "rst"
}
}
}
}

How to extract values from multidimensional array grouped by some value inside it using PHP?

I have an array that looks like this:-
Array (
[0] => Array ( [id] => 10 [group] => 11 )
[1] => Array ( [id] => 11 [group] => 13 )
[2] => Array ( [id] => 12 [group] => 13 )
[3] => Array ( [id] => 13 [group] => 13 )
[4] => Array ( [id] => 14 [group] => 16 )
[5] => Array ( [id] => 15 [group] => 16 )
[6] => Array ( [id] => 16 [group] => 16 )
)
For each different group in this array i want to create array that stores id's.
In my example i have 3 groups, so i want to get 3 arrays like this:
Array ( [0] => 10)
Array ( [0] => 11
[1] => 12
[2] => 13)
Array ( [0] => 14
[1] => 15
[2] => 16)
Is it possible if it is how can i do it?
This should help you get started.
https://iconoun.com/demo/temp_icold.php
<?php // demo/temp_icold.php
/**
* Manipulate multi-dimensional arrays
*
* https://stackoverflow.com/questions/45422046/how-to-extract-values-from-multidimensional-array-grouped-by-some-value-inside-i
*/
error_reporting(E_ALL);
echo '<pre>';
$original = Array (
'0' => Array ( 'id' => 10, 'group' => 11 ),
'1' => Array ( 'id' => 11, 'group' => 13 ),
'2' => Array ( 'id' => 12, 'group' => 13 ),
'3' => Array ( 'id' => 13, 'group' => 13 ),
'4' => Array ( 'id' => 14, 'group' => 16 ),
'5' => Array ( 'id' => 15, 'group' => 16 ),
'6' => Array ( 'id' => 16, 'group' => 16 ),
);
print_r($original);
foreach ($original as $arr)
{
$ndx = 'group' . $arr['group'];
$out[$ndx][] = $arr['id'];
}
print_r($out);
You can achieve this through many different methods, but the simplest is probably a foreach() loop. In the example below I am looping through $a (your sample array) and building up a new array called $grouped with the index as the group attributes value.
In my example I am not duplicating the ID's inside of $group. If you wanted duplicates you could remove the second if statement.
$a = [
['id' => 10, 'group' => 11],
['id' => 11, 'group' => 13],
['id' => 12, 'group' => 13],
['id' => 13, 'group' => 13],
['id' => 14, 'group' => 16],
['id' => 15, 'group' => 16],
['id' => 16, 'group' => 16],
];
$grouped = [];
foreach ($a as $entry) {
if (! array_key_exists($entry['group'], $grouped)) {
$grouped[$entry['group']] = [];
}
if (! in_array($entry['id'], $grouped[$entry['group']])) {
$grouped[$entry['group']][] = $entry['id'];
}
}
var_dump($grouped);
The example outputs the following:
array(3) {
[11]=>
array(1) {
[0]=>
int(10)
}
[13]=>
array(3) {
[0]=>
int(11)
[1]=>
int(12)
[2]=>
int(13)
}
[16]=>
array(3) {
[0]=>
int(14)
[1]=>
int(15)
[2]=>
int(16)
}
}
$result_array = array();
foreach($array_name as $sub_array){
$result_array[$sub_array['group']][] = $sub_array['id'];
}
This will loop through your input array and create a result two dimensional array indexed by your group values. To extract a group result just index for the group as such: $result_array['GROUP_NUMBER'];
Here is my take on this:
<?php
$arr = array(
array("id"=>10,"group"=>11),
array("id"=>11,"group"=>13),
array("id"=>12,"group"=>13),
array("id"=>13,"group"=>13),
array("id"=>14,"group"=>16),
array("id"=>15,"group"=>16),
array("id"=>16,"group"=>16)
);
echo "<pre>".print_r(groupsToArrays($arr),true)."</pre>";
function groupsToArrays($arr, $groupkey = "group") {
$main = array();
$group = 0;
$arr[] = array("id"=>"end", $groupkey => "0");
foreach($arr as $key => $value) {
if($group != $value[$groupkey]) {
if($key != 0) $main[$group] = $tempArray;
if($value['id'] == "end") continue;
$group = $value[$groupkey];
$tempArray = array();
}
$tempArray[] = $value;
}
return $main;
}
This function will loop through your array and check the $groupkey key and will add every match to it's own array.
This is the return:
Array
(
[11] => Array
(
[0] => Array
(
[id] => 10
[group] => 11
)
)
[13] => Array
(
[0] => Array
(
[id] => 11
[group] => 13
)
[1] => Array
(
[id] => 12
[group] => 13
)
[2] => Array
(
[id] => 13
[group] => 13
)
)
[16] => Array
(
[0] => Array
(
[id] => 14
[group] => 16
)
[1] => Array
(
[id] => 15
[group] => 16
)
[2] => Array
(
[id] => 16
[group] => 16
)
)
)
So now you can access that group array by doing:
$groups = groupsToArrays($arr);
print_r($groups[$groupID]);

how to convert associative array in to one array

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

PHP - Two dimensional array

I'm quite new to PHP and I'm havint some trouble understanding how I'm supposed to turn something like this:
Array
(
[name] => Array
(
[0] => Bob
[1] => Tom
[2] => Ryan
[3] => Lisa
[4] => Peter
)
[age] => Array
(
[0] => 23
[1] => 33
[2] => 43
[3] => 33
[4] => 29
)
)
Into this kind of an array:
Array
(
[person] => Array
(
[name] => Bob
[age] => 23
)
[person] => Array
(
[name] => Tom
[age] => 33
)
)
So I wan't to be able to have a person key, rather than name and age keys. And to put identical indexes from name and age into this person key. How would I go about achieving this?
Thanks.
It is impossible to have many person keys in array because keys have to be unique.
Just try with:
$input = [
'name' => ['Bob', 'Tom', 'Ryan', 'Lisa', 'Peter'],
'age' => [23, 33, 43, 33, 29],
];
$output = array_map(function($name, $age) {
return ['name' => $name, 'age' => $age];
}, $input['name'], $input['age']);
var_dump($output);
Output:
array (size=5)
0 =>
array (size=2)
'name' => string 'Bob' (length=3)
'age' => int 23
1 =>
array (size=2)
'name' => string 'Tom' (length=3)
'age' => int 33
2 =>
array (size=2)
'name' => string 'Ryan' (length=4)
'age' => int 43
3 =>
array (size=2)
'name' => string 'Lisa' (length=4)
'age' => int 33
4 =>
array (size=2)
'name' => string 'Peter' (length=5)
'age' => int 29
Easiest way is this:
// Create a main array for the 'people' to be stored in
$people = array();
// Create a person
$bob = array('name' => 'Bob', 'age' => 23);
// Add that person into the 'people' array
$people[] = $bob;
// Repeat as many times a necessary
$tom = array('name' => 'Tom', 'age' => 33);
$people[] = $tom;
$ryan = array('name' => 'Ryan', 'age' => 43);
$people[] = $ryan;
To see the output do:
var_dump($people);
Should produce something like:
array(3) {
[0]=>
array(2) {
["name"]=>
string(3) "Bob"
["age"]=>
int(23)
}
[1]=>
array(2) {
["name"]=>
string(3) "Tom"
["age"]=>
int(33)
}
[2]=>
array(2) {
["name"]=>
string(4) "Ryan"
["age"]=>
int(43)
}
}
This is because you can automatically append items to the end of arrays without needing to specify the key you wish to insert them at. This is what we're doing with the lines:
$people[] = $bob;
Essentially that says, add the variable '$bob' to the next available slot in the array. As the array is initially empty, that happens to be the '0' key, and so on.
The key, by definition, must be unique. What you can do is, make an array called $persons, with the following data:
Array (
[1] => Array (
[name] => Bob
[age] => 23
)
[2] => Array (
[name] => Tom
[age] => 33
)
...
)
You can do this as follows:
$persons = Array();
for($i = 0; $i < sizeof($arr["name"]); $i++) {
$persons[$i]["name"] = $arr["name"][$i];
$persons[$i]["age"] = $arr["age"][$i];
}
Sample output:
Array
(
[0] => Array
(
[name] => Bob
[age] => 23
)
[1] => Array
(
[name] => Tom
[age] => 33
)
[2] => Array
(
[name] => Ryan
[age] => 43
)
...
)
like
$array=new Array();
$array[]=array('name'=>'Jhon Doe','age'=>23]
and so on for each person you want to store.

Categories