I have 2 array as below(Array-1, Array-2) and i wanted to merge as a single array as below (New-Array) based on the below condition
Contition : (if Array-1(hID) = Array-2(hID) then megre as below)
Array-1
Array
(
[0] => Array
(
[hID] => 107
[env] => DEV
[serv] => server1
)
[1] => Array
(
[hID] => 122
[env] => DEV
[serv] => server2
)
Array-2
Array
(
[107] => Array
(
[hID] => 107
[cpu] => 32
[mem] => 24
)
[122] => Array
(
[hID] => 122
[cpu] => 16
[mem] => 24
)
New-Array
Array
(
[0] => Array
(
[hID] => 107
[env] => DEV
[serv] => server1
[cpu] => 32
[mem] => 24
)
[1] => Array
(
[hID] => 122
[env] => DEV
[serv] => server2
[cpu] => 16
[mem] => 24
)
If second array always has same keys as hID values then you can do the following:
$newArray = [];
foreach ($array1 as $item) {
if (isset($array2[$item['hID']])) {
$newArray[] = array_merge($item, $array2[$item['hID']]);
}
}
Or you can always create such array (key is the same as hID value) with:
$array2 = array_combine(
array_column($array2, 'hID'),
$array2
);
You can try this :
The test arrays :
$array_1 = [
0 => [
"hID" => 107,
"env" => "DEV",
"serv" => "server1"
],
1 => [
"hID" => 122,
"env" => "DEV",
"serv" => "server2"
]
];
$array_2 = [
0 => [
"hID" => 107,
"cpu" => 32,
"mem" => 24
],
1 => [
"hID" => 122,
"cpu" => 16,
"mem" => 24
]
];
The code to merge both arrays :
$new_array = [];
for($i=0;$i<count($array_1);$i++) {
for($j=0;$j<count($array_2);$j++) {
if ($array_1[$i]['hID'] === $array_2[$j]['hID']) {
$new_array[] = array_merge($array_1[$i], $array_2[$j]);
}
}
}
The output :
var_dump($new_array);
array(2) {
[0]=>
array(5) {
["hID"]=>
int(107)
["env"]=>
string(3) "DEV"
["serv"]=>
string(7) "server1"
["cpu"]=>
int(32)
["mem"]=>
int(24)
}
[1]=>
array(5) {
["hID"]=>
int(122)
["env"]=>
string(3) "DEV"
["serv"]=>
string(7) "server2"
["cpu"]=>
int(16)
["mem"]=>
int(24)
}
}
Test here : http://sandbox.onlinephpfunctions.com/
if($array1[hID] == $array2[hID]){
$Array3 = array_merge($array1, $array2);
}
Related
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"
}
}
}
}
Array ( [11] => Array ( [0] => A [1] => Attempt ) [ 12] => Array ( [0] => 0 [1] => None ) [ 13] => Array ( [0] => 0 [1] => None ) [ 14] => Array ( [0] => 0 [1] => None ) [ 15] => Array ( [0] => 0 [1] => None ) [ 16] => Array ( [0] => 0 [1] => None ) )
This is my array but i want in below STRING format:
11=>A=>Attempt,12=>0=>None,13=>0=>None,14=>0=>None,15=>0=>None,16=>0=>None
1. $keys=array_keys($total_answer)
2. for($i=0;$i<count($keys);$i++)
3. {
4. for($j=0;$j<count($total_answer[$keys[$i]]);$j++)
5. {
6. echo $total_answer[$keys[$i]][$j]
7. //Here I am getting confuse to make string
Thank You In Advance:)
One way to do it,
<?php
$array = array ( "11" => array ( "0" => "A" ,"1" => "Attempt" ) ,"12" => array ( "0" => 0, "1" => "None" ) ,"13" => array ( "0" => 0, "1" => "None" ) ,"14" => array ( "0" => 0 ,"1" => "None" ), "15" => array ( "0" => 0, "1" => "None" ), "16" => array ( "0" => 0, "1" => "None" ) );
foreach($array as $key=>$value){
$expected[] = $key.'=>'.$value[0].'=>'.$value[1];
}
echo implode(',',$expected);
?>
WORKING DEMO: https://3v4l.org/TDb0A
One foreach is enough
$out = [];
foreach ($total_answer as $k=>$v)
{
array_unshift($v, $k);
$out[] = implode('=>', $v);
}
echo implode(',', $out);
I have 2 array
$arr1 = Array (
[0] => Array ( [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1 )
[1] => Array ( [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0 ))
and
$arr2 = Array (
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 )
[1] => Array ( [id] => 3944 [customer_id] => 1[Expire] => 2019-05-14 )
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 )
)
and try to put first array key and value [paid]=>1 or 0 in second array if customer id and expire match like
Array (
[0] => Array ( [id] => 3943 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[1] => Array ( [id] => 3944 [customer_id] => 1 [Expire] => 2019-05-14 [paid] => 1)
[2] => Array ( [id] => 4713 [customer_id] => 2 [Expire] => 2019-06-20 [paid] => 0)
)
I try to merge array in php but not get exact what i want. Is there any php function to do it?.
Loop your second array $arr2, and find the index of the first array $arr1 where the column customer_id is the same as in the current iteration of $arr2. array_search() returns that index, which we can then use to fetch the paid index of that array. Then we append it to our array $arr2, by doing $a['paid'] = $paid;.
Since we loop the array by reference (the & before $a in the loop), the changes we make to it, will be applied back to the original array.
foreach ($arr2 as &$a) {
$customerID = $a['customer_id']; // This customer ID
$arr1_key = array_search($customerID, array_column($arr1, 'customer_id')); // Find the index of this customerID in the first array
$paid = $arr1[$arr1_key]['paid']; // Find the paid value matching that customer ID
$a['paid'] = $paid;
}
Live demo at https://3v4l.org/Meqtu
Update
If you need it to match the ID as well as the expiration date, then use array_filter() to fetch the array-element within $arr1 that matches the date and the ID. Using reset(), we use the first element in that array.
foreach ($arr2 as &$a) {
// Find the sub-array of $arr1 that matches this array's date and ID
$arr1_match = array_filter($arr1, function($v) use ($a) {
return $v['customer_id'] == $a['customer_id'] && $v['Expire'] == $a['Expire'];
});
// Get the first element from the result
$paid = reset($arr1_match)['paid'];
// Append the paid-value to this array (done by reference)
$a['paid'] = $paid;
}
Live demo at https://3v4l.org/mov6d
sometimes things can be done in hard way:)
<?php
$arr1 = [
['customer_id' => 1, 'Expire' => '2019-05-14', 'paid' => 1],
['customer_id' => 2, 'Expire' => '2019-06-20', 'paid' => 0],
];
$arr2 = [
['id' => 3943, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3944, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3945, 'customer_id' => 2, 'Expire' => '2019-05-14'],
['id' => 4713, 'customer_id' => 2, 'Expire' => '2019-06-20'],
];
foreach ($arr2 as &$item2) {
foreach ($arr1 as $item1) {
if (
$item2['customer_id'] === $item1['customer_id']
&& $item2['Expire'] === $item1['Expire']
) {
$item2['paid'] = $item1['paid'];
break;
}
}
}
unset($item2);
var_dump($arr2);
If you cannot change the layout of the first array I think it will be best to first create an intermediate array that keeps a record of all expire dates for every customer.
The following implementation does not require you to use a nested loop.
<?php
$arr1 = [
['customer_id' => 1, 'Expire' => '2019-05-14', 'paid' => 1],
['customer_id' => 2, 'Expire' => '2019-06-20', 'paid' => 0],
];
$arr2 = [
['id' => 3943, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3944, 'customer_id' => 1, 'Expire' => '2019-05-14'],
['id' => 3945, 'customer_id' => 2, 'Expire' => '2019-05-14'],
['id' => 4713, 'customer_id' => 2, 'Expire' => '2019-06-20'],
];
// Create a list of all paid, expiry dates, keyed by customer_id
$payed = [];
foreach ($arr1 as $item) {
if (!isset($payed[$item['customer_id']])) {
$payed[$item['customer_id']] = [];
}
$payed[$item['customer_id']][] = $item['Expire'];
}
// Lookup the customer and expire date for every entry
$arr2 = array_map(function($item) use ($payed) {
$item['paid'] = in_array($item['Expire'], $payed[$item['customer_id']] ?? []);
return $item;
}, $arr2);
Result:
Array
(
[0] => Array
(
[id] => 3943
[customer_id] => 1
[Expire] => 2019-05-14
[paid] => 1
)
[1] => Array
(
[id] => 3944
[customer_id] => 1
[Expire] => 2019-05-14
[paid] => 1
)
[2] => Array
(
[id] => 3945
[customer_id] => 2
[Expire] => 2019-05-14
[paid] =>
)
[3] => Array
(
[id] => 4713
[customer_id] => 2
[Expire] => 2019-06-20
[paid] => 1
)
)
See demo
This can fix the issue :
$arr1 = array(
["customer_id"=>1,"Expire"=> "2019-05-14", "paid"=>1],
["customer_id"=>2,"Expire"=> "2019-06-20", "paid"=>0]
);
$arr2 = array(
["id"=>3943, "customer_id"=>1,"Expire"=> "2019-05-14"],
["id"=>3944,"customer_id"=>2,"Expire"=> "2019-06-20"],
["id"=>4713,"customer_id"=>1,"Expire"=> "2019-05-14"]
);
$result= array();
function getRowByCustomerID($id, $array){
foreach($array as $value){
if($value['customer_id'] ==$id){
return $value;
}
}
return null;
}
foreach($arr2 as $subarr){
$object = getRowByCustomerID($subarr['customer_id'],$arr1 );
if(!is_null($object)){
$object['id']=$subarr['id'];
$result[]= $object;
}
}
var_dump($result);
the output is similar to what you are looking for :
array(3) {
[0]=>
array(4) {
["customer_id"]=>
int(1)
["Expire"]=>
string(10) "2019-05-14"
["paid"]=>
int(1)
["id"]=>
int(3943)
}
[1]=>
array(4) {
["customer_id"]=>
int(2)
["Expire"]=>
string(10) "2019-06-20"
["paid"]=>
int(0)
["id"]=>
int(3944)
}
[2]=>
array(4) {
["customer_id"]=>
int(1)
["Expire"]=>
string(10) "2019-05-14"
["paid"]=>
int(1)
["id"]=>
int(4713)
}
}
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 1 year ago.
This is my array and i want 60 , 20, 39, 70,12, 29,31,72,59 in a single array. one-dimensional array.
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
)Íž
my try was
foreach($marks as $name=>$score)
{
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}
But when i am printing this array it again generate three array.
on print_r($array); its showing this output.
Array ( [0] => 60 [1] => 20 [2] => 39 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 [6] => 31 [7] => 72 [8] => 59 )
is there any method to get only last array from the above array.or any other solution.
Try this to flatten the array:
<?php
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
);
function array_values_recursive($array)
{
$arrayValues = array();
foreach ($array as $value)
{
if (is_scalar($value) OR is_resource($value))
{
$arrayValues[] = $value;
}
elseif (is_array($value))
{
$arrayValues = array_merge($arrayValues, array_values_recursive($value));
}
}
return $arrayValues;
}
var_dump(array_values_recursive($marks));
Output:
array(9) { [0]=> int(60) [1]=> int(20) [2]=> int(39) [3]=> int(70) [4]=> int(12) [5]=> int(29) [6]=> int(31) [7]=> int(72) [8]=> int(59) }
This custom function was taken from: http://php.net/manual/en/function.array-values.php
you can do in either traditional way i.e. foreach loop and also can use iterator. have a look on below solution:
1) using foreach loop and array_merge function
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
);
$new_array = array();
foreach ($marks as $mark) {
$new_array = array_merge($new_array, array_values($mark));
}
print_r($new_array);
2) using ArrayIterator:
$new_array = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($marks));
foreach ($iterator as $key => $value) {
$new_array[] = $value;
}
print_r($new_array);
In both solution Output will be:
Array
(
[0] => 60
[1] => 20
[2] => 39
[3] => 70
[4] => 12
[5] => 29
[6] => 31
[7] => 72
[8] => 59
)
Because you're dumping $array inside the first foreach loop :)
Your sound like you may be declare your $array in for loop ,if you do so you will get three arrays.So declare outside of for loop will be get single array
$array = array(); //correct
foreach($marks as $name=>$score)
{
//$array = array(); //incorrect
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}
var_dump($array);
foreach($marks as $name=>$score)
{
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}
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)
}
}