unset values null array multidimensional php [duplicate] - php

This question already has answers here:
Recursively remove empty elements and subarrays from a multi-dimensional array
(8 answers)
How to remove null values in multi-dimensional array?
(7 answers)
Closed 1 year ago.
this is my first time on stackoverflow so sorry if I do something wrong. I would also appreciate your advice.
I have the next Array:
$dataPayment= [
"operationType" => null
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"urlOk" => null
"urlKo" => null
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
"subscription" => array:2 [
"startDate" => null
"endDate" => null
]
]
And I want delete the null values. With array_filter also delete values 0, but I need those values 0. I tried with the following method:
private function arrayUnset( $dataPayment )
{
foreach( $dataPayment as $key => $value )
{
if( is_array( $dataPayment[ $key ] ) )
{
$this->arrayUnset( $dataPayment[ $key ] );
}
if( $value === null || $value === "" )
{
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}
But, only delete the first value.
$dataPayment = [
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"urlOk" => null
"urlKo" => null
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
"subscription" => array:2 [
"startDate" => null
"endDate" => null
]
]
And I would need the following array:
$dataPayment = [
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
]
Can you help me please?. Thanks.

That code does not seem to delete the 0 valued entries, but you do need to pass the parameter by reference if you want to see the changes in the calling process
$Payment = [
"operationType" => null,
"terminal" => 12345,
"payment" => [
"terminal" => 12345,
"order" => "1234519997",
"amount" => 100,
"currency" => "EUR",
"secure" => 0,
"idUser" => 123456789,
"tokenUser" => "zidkeKeu68Kld",
"urlOk" => null,
"urlKo" => null,
"originalIp" => "1.130.151.28",
"methodId" => 1,
"trxType" => "N",
"userInteraction" => 1,
"scaException" => "MIT"
],
"subscription" => [
"startDate" => null,
"endDate" => null
]
];
class xxx
{
private function arrayUnset( &$dataPayment )
{
foreach( $dataPayment as $key => $value ) {
if( is_array( $dataPayment[ $key ] ) ) {
$this->arrayUnset( $dataPayment[ $key ] );
}
if( $value === null || $value === "" ) {
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}
public function zzz($data)
{
return $this->arrayUnset($data);
}
}
$obj = new xxx;
print_r($obj->zzz($Payment));
RESULTS
Array
(
[terminal] => 12345
[payment] => Array
(
[terminal] => 12345
[order] => 1234519997
[amount] => 100
[currency] => EUR
[secure] => 0
[idUser] => 123456789
[tokenUser] => zidkeKeu68Kld
[originalIp] => 1.130.151.28
[methodId] => 1
[trxType] => N
[userInteraction] => 1
[scaException] => MIT
)
[subscription] => Array
(
)
)

You should passing argument by reference.
private function arrayUnset( &$dataPayment )
{
foreach( $dataPayment as $key => $value )
{
if( is_array( $dataPayment[ $key ] ) )
{
$dataPayment[ $key ] = $this->arrayUnset($value);
}
if( $value === null || $value === "" )
{
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}

Array filters remove null elements, so map your array using mapWithKeys, if each property is an array, use array_filter(). Run a secondary filter, to remove the empty array.
$collection = collect($dataPayment);
$result = $collection->mapWithKeys(function ($item, $key) {
if (is_array($item)) {
$item = array_filter($item);
}
return [$key => $item];
})->filter()->all();
This should produce the expected results. If any problems with the code, please write.

You are not storing the return from your recursive calls.
Try:
<?php
$Payment = [
"operationType" => null,
"terminal" => 12345,
"payment" => [
"terminal" => 12345,
"order" => "1234519997",
"amount" => 100,
"currency" => "EUR",
"secure" => 0,
"idUser" => 123456789,
"tokenUser" => "zidkeKeu68Kld",
"urlOk" => null,
"urlKo" => null,
"originalIp" => "1.130.151.28",
"methodId" => 1,
"trxType" => "N",
"userInteraction" => 1,
"scaException" => "MIT"
],
"subscription" => [
"startDate" => null,
"endDate" => null
]
];
function arrayUnset($dataPayment) {
foreach($dataPayment as $key => $value)
if(is_array($dataPayment[$key]))
$dataPayment[$key]=arrayUnset($dataPayment[$key]);
else if ($value==null || $value=="")
unset($dataPayment[$key]);
return $dataPayment;
}
print_r(arrayUnset($Payment));
Output:
Array
(
[terminal] => 12345
[payment] => Array
(
[terminal] => 12345
[order] => 1234519997
[amount] => 100
[currency] => EUR
[secure] => 0
[idUser] => 123456789
[tokenUser] => zidkeKeu68Kld
[originalIp] => 1.130.151.28
[methodId] => 1
[trxType] => N
[userInteraction] => 1
[scaException] => MIT
)
[subscription] => Array
(
)
)
Teh Playground!

Related

How to create new row instead of using the same one?

I have the following array:
$original_array = [
[
"group" => "g1",
"department" => "d1",
"team" => null,
"data_col1" => "some_data1",
"data_col2" => "some_data2"
],
[
"group" => "g1",
"department" => "d1",
"team" => null,
"data_col1" => "some_data3",
"data_col2" => "some_data4"
],
[
"group" => "g1",
"department" => "d1",
"team" => "t3",
"data_col1" => "some_data5",
"data_col2" => "some_data6"
],
[
"group" => "g4",
"department" => "d6",
"team" => "t11",
"data_col1" => "some_data7",
"data_col2" => "some_data8"
]
];
I want to "group" the array into common group/department/team.
I tried the following - I created a new array, then I assign the relevant keys (group/department/team) and otherwise I assign the value:
$new_array = [];
foreach ($original_array as $row) {
foreach ($row as $key => $value) {
if ($key === "group" || $key === "department" || $key === "team") {
$new_array[$key] = $value;
} else {
$new_array[] = $value;
}
}
}
The expected result is:
[
0 => [
group => "g1",
department => "d1",
team => null,
data => [
0 => [data_col1 => "some_data1", data_col2 => "some_data2"],
1 => [data_col1 => "some_data3", data_col2 => "some_data4"]
],
1 => [
group => "g1",
department => "d1",
team => "t3",
data => [
0 => [data_col1 => "some_data5", data_col2 => "some_data6"]
],
2 => [
group => "g4",
department => "d6",
team => "t11",
data => [
0 => [data_col1 => "some_data7", data_col2 => "some_data8"]
]
]
But the result is:
[
"group" => "g4"
"department" => "d6"
"team" => "t11"
0 => "some_data1"
1 => "some_data2"
2 => "some_data3"
3 => "some_data4"
4 => "some_data5"
5 => "some_data6"
6 => "some_data7"
7 => "some_data8"
]
why? Looks like it only assigns values to the last row in the original array
This code should give the good result :
foreach ($original_array as $row) {
$key = md5($row['group'] . $row['department'] . $row['team']);
if(!isset($new_array[$key])){
$new_array[$key] = [
'group' => $row['group'],
'department' => $row['department'],
'team' => $row['team'],
'data' => [],
];
}
$data = [];
foreach ($row as $k => $v) {
if ($k !== "group" AND $k !== "department" AND $k !== "team") {
$data[$k] = $v;
}
}
$new_array[$key]['data'][] = $data;
}
This give me that :
Array
(
[336a26e12ea082ff360f8482891e137c] => Array
(
[group] => g1
[department] => d1
[team] =>
[data] => Array
(
[0] => Array
(
[data_col1] => some_data1
[data_col2] => some_data2
)
[1] => Array
(
[data_col1] => some_data3
[data_col2] => some_data4
)
)
)
[f06623fdd946c84a0c0c30378ba3f6f5] => Array
(
[group] => g1
[department] => d1
[team] => t3
[data] => Array
(
[0] => Array
(
[data_col1] => some_data5
[data_col2] => some_data6
)
)
)
[0b284dc4a7dac108ec2b1205a6484056] => Array
(
[group] => g4
[department] => d6
[team] => t11
[data] => Array
(
[0] => Array
(
[data_col1] => some_data7
[data_col2] => some_data8
)
)
)
)

How to check the condition in given three array

I am having three arrays
topicsSelected
relavantGroups
topicAssingned
$topicsSelected = [ "T-100","T-600"];
$relavantGroups = [[ "id" => "G-001","name" => "3 A","active"=> false ], ["id"=> "G-002","name"=> "3 B","active"=> false] ];
$topicAssingned = [
"G-001" => [
"groupID" => "G-001",
"groupName" => "3 A",
"topics" => [
"T-100" => [
"topicID" => "T-100"
],
"T-200" => [
"topicID" => "T-200"
]
]
],
"G-002" => [
"groupID" => "G-002",
"groupName" => "3 B",
"topics" => [
"T-400" => [
"topicID" => "T-400"
],
"T-500" => [
"topicID" => "T-500"
]
]
],
];
$topicsSelected array values(T-100 or T-600) at least one value should present in $topicAssingned array, based on groupID(G-001). $topicAssingned under topics , topicID : T-100 is present , so Disable : D
$topicsSelected array values(T-100 or T-600) at least one value should present in $topicAssingned array, based on groupID(G-002). $topicAssingned under topics , topicID : T-100 & T-600 is not present , so Disable : A
Expected output:
[
"id": "G-001",
"name": "3 A",
"active": false,
"Disable" : "D"
],
[
"id": "G-002",
"name": "3 B",
"active": false,
"Disable" : "A"
]
My Code
foreach ($relavantGroups as &$g) {
$found = false;
foreach ($topicAssingned as $key => $assigned) {
if ($key === $g["id"]) {
$found = true;
break;
}
}
$g["disable"] = $found ? "D" : "A";
}
echo "<pre>";
print_r($relavantGroups);
My Output
Array
(
[0] => Array
(
[id] => G-001
[name] => 3 A
[active] =>
[disable] => D
)
[1] => Array
(
[id] => G-002
[name] => 3 B
[active] =>
[disable] => D
)
)
You can try this snippet,
foreach ($relavantGroups as &$g) {
$found = false;
foreach ($topicAssingned as $key => $assigned) {
if ($key === $g["id"]) {
$temp = array_keys($assigned['topics']); // fetching all topic ids
$intr = array_intersect($topicsSelected, $temp); // checking if there are any matching values between topicSelected and traversed values
$found = (!empty($intr) ? true : false); // if found return and break
break;
}
}
$g["disable"] = $found ? "D" : "A";
}
print_r($relavantGroups);
array_intersect — Computes the intersection of arrays
array_keys — Return all the keys or a subset of the keys of an array
Output
Array
(
[0] => Array
(
[id] => G-001
[name] => 3 A
[active] =>
[disable] => D
)
[1] => Array
(
[id] => G-002
[name] => 3 B
[active] =>
[disable] => A
)
)
Demo

how to sort array data in alphabetic key order in php

my collection of data in array which is shown below the index key is A,B,C but i want to store these key in "key" and its key letter's words in "dishes" key
array:3 [
"A" => array:4 [
0 => 37
1 => "Algerian"
2 => 6
3 => "American"
]
"B" => array:6 [
0 => 27
1 => "Belgian"
2 => 20
3 => "Brazilian"
]
and so on..
i wanna sort this array like aplhabetic order as shown below
array:10 [
0 => array:2 [
"key" => "A"
"dishes" => array:2 [
0=>array:2[
"id" => 37
"type" => "Algerian"
],
1=>array:2[
"id" => 6
"type" => "American"
]
]
]
1 => array:2 [
"key" => "B"
"dishes" => array:2 [
0=>array:2[
"id" => 27
"type" => "Belgian"
],
1=>array:2[
"id" => 20
"type" => "Brazilian"
]
]
]
and so on...
This would be a possible solution:
<?php
$input = [
'A' => [
0 => 37,
1 => "Algerian",
2 => 6,
3 => "American"
],
'B' => [
0 => 27,
1 => "Belgian",
2 => 20,
3 => "Brazilian"
]
];
$output = [];
array_walk($input, function($values, $key) use (&$output) {
$entry = [
'key' => $key,
'dishes' => []
];
foreach(array_chunk($values, 2) as $chunk) {
$entry['dishes'][] = [
'id' => $chunk[0],
'type' => $chunk[1]
];
}
$output[] = $entry;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => Array
(
[key] => A
[dishes] => Array
(
[0] => Array
(
[id] => 37
[type] => Algerian
)
[1] => Array
(
[id] => 6
[type] => American
)
)
)
[1] => Array
(
[key] => B
[dishes] => Array
(
[0] => Array
(
[id] => 27
[type] => Belgian
)
[1] => Array
(
[id] => 20
[type] => Brazilian
)
)
)
)
You have to loop through the original array to create your new structure. Then you can use the ksort function to sort them.
$newArr = new array();
for ($arr as $elem) {
$dishArr = new array();
for($elem['dishes'] as $dish) {
$dishArr[] = $dish['id'];
$dishArr[] = $dish['type'];
}
$newArr[$elem['key']] = $dishArr;
}
ksort($newArr);

How to get other array value if match?

Array 1 output
Array (
[0] => Array ( [ID] => 335 [userid] => 4 [username] => demo [media_id] => 17 )
[1] => Array ( [ID] => 436 [userid] => 4 [username] => demo [media_id] => 18 )
[2] => Array ( [ID] => 637 [userid] => 4 [username] => demo [media_id] => 19 )
[3] => Array ( [ID] => 838 [userid] => 4 [username] => demo [media_id] => 20 )
);
Array 2 output
Array (
[1] => Array ( [ID] => 35 [userid] => 4 [media_id] => 17 )
[2] => Array ( [ID] => 36 [userid] => 4 [media_id] => 18 )
);
How to get other array value if match? I need if media_id and userid of array 2 match in array 1 then how to get perticuler ID and username from array 1 in foreach loop of array 2 ?
Update
$array1 = array (
0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "17" ),
1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "18" ),
2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
);
$array2 = array (
1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
);
foreach($array2 as $array) {
foreach($array1 as $get_data) {
if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']){
$get_result[] = //get_data true;
} else {
$get_result[] = //get_data false;
}
}
//get ID and username or show false value
}
Final answer
foreach($array2 as $array) {
$return = "false";
foreach($array1 as $get_data) {
if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
$get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
$return = "true";
}
}
if($return = "false"){
echo false;
}
}
If I understood well your question (I'm not sure), this should work:
foreach($array2 as $array) {
foreach($array1 as $get_data) {
if($array1['media_id'] == $get_data['media_id'] && $array1['userid'] == $get_data['userid']) {
$get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
}
}
}
if (count($get_result) == 0) {
$get_result[] = false;
}
Not sure about your real needs, but #gmc gave you (part of ? all ?) what you need IMHO
<?php
$array1 = array (
0 => array ( "ID" => "335", "userid" => "4", "username" => "demo", "media_id" => "117" ),
1 => array ( "ID" => "436", "userid" => "4", "username" => "demo", "media_id" => "118" ),
2 => array ( "ID" => "637", "userid" => "4", "username" => "demo", "media_id" => "19" ),
3 => array ( "ID" => "838", "userid" => "4", "username" => "demo", "media_id" => "20" )
);
$array2 = array (
1 => array ( "ID" => "35", "userid" => "4", "media_id" => "17" ),
2 => array ( "ID" => "36", "userid" => "4", "media_id" => "18" )
);
$get_result = array();
foreach($array2 as $array) {
foreach($array1 as $get_data) {
if( ($array['media_id'] == $get_data['media_id']) && ($array['userid'] == $get_data['userid'])) {
$get_result[] = ['ID' => $get_data['ID'], 'username' => $get_data['username']];
}
}
}
if (count($get_result) == 0) {
echo"false";
}
else {
echo"true"; print_r($get_result); }
?>
/* I modified values to 117 & 118 -> returns "false" */
/* If you set values to 17 & 18 -> returns "true" */

group mysql results in multidimensional array

I have the following:
$variants = [
0 => [
"variant_name" => "iPhone 5",
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0
],
1 => [
"variant_name" => "Red",
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0
],
2 => [
"variant_name" => "iPhone 6s Plus",
"sku_id" => "4",
"sku" => "GLC-IPH6SP",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0
],
3 => [
"variant_name" => "iPhone 6s",
"sku_id" => "13",
"sku" => "GLC-IPH6S",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0
]
]
I would like to put them in the following array
0 => [
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 4', 'Red'],
"option1" => 'iPhone4',
"option2" => 'Red',
"option3" => null
],
1 => [
"sku_id" => "4",
"sku" => "GLC-IPH6SP",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 6s Plus'],
"option1" => 'iPhone 6s Plus',
"option2" => null,
"option3" => null
],
2 => [
"sku_id" => "13",
"sku" => "GLC-IPH6S",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 6s'],
"option1" => 'iPhone 6s',
"option2" => null,
"option3" => null
]
I can't fill the options with each variant_name
I can't set the option1, option2, option3 with each corresponding variant_name
I've tried a simple foreach($variants as $v) loop on the first array and I got it working until options, option1, option2, option3 from which I get the repeating values.
I just can't figure it out how to do it, any suggestions?
You could use a simple foreach() and perhaps a for(). The for() here is a little inefficient because it runs every time, so it's highly repetitive and continually overwrites...but it works:
foreach($variants as $rows) {
$sku[$rows['sku_id']]['sku_id'] = $rows['sku_id'];
$sku[$rows['sku_id']]['sku'] = $rows['sku'];
$sku[$rows['sku_id']]['stock_total'] = $rows['stock_total'];
$sku[$rows['sku_id']]['stock_left'] = $rows['stock_left'];
$sku[$rows['sku_id']]['retail_price'] = $rows['retail_price'];
$sku[$rows['sku_id']]['on_sale_price'] = $rows['on_sale_price'];
$sku[$rows['sku_id']]['options'][] = $rows['variant_name'];
for($i = 0; $i < 3; $i++)
$sku[$rows['sku_id']]['option'.($i+1)] = (isset($sku[$rows['sku_id']]['options'][$i]))? $sku[$rows['sku_id']]['options'][$i] : NULL;
}
echo print_r(array_values($sku));
Gives you:
Array
(
[0] => Array
(
[sku] => GLC-IPH5REDXXXL
[stock_total] => 10
[stock_left] => 10
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 5
[1] => Red
)
[option1] => iPhone 5
[option2] => Red
[option3] =>
)
[1] => Array
(
[sku] => GLC-IPH6SP
[stock_total] => 5
[stock_left] => 5
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 6s Plus
)
[option1] => iPhone 6s Plus
[option2] =>
[option3] =>
)
[2] => Array
(
[sku] => GLC-IPH6S
[stock_total] => 5
[stock_left] => 5
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 6s
)
[option1] => iPhone 6s
[option2] =>
[option3] =>
)
)
Solution
$result = [];
foreach($variants as $v) {
$result[$v['sku_id']]['sku_id'] = $v['sku_id'];
$result[$v['sku_id']]['sku'] = $v['sku'];
$result[$v['sku_id']]['stock_left'] = $v['stock_left'];
$result[$v['sku_id']]['retail_price'] = price($v['retail_price']);
$result[$v['sku_id']]['options'][] = $v['variant_name'];
if(isset($result[$v['sku_id']]['options'][0])) {
$result[$v['sku_id']]['option1'] = $result[$v['sku_id']]['options'][0];
}
else {
$result[$v['sku_id']]['option1'] = null;
}
if(isset($result[$v['sku_id']]['options'][1])) {
$result[$v['sku_id']]['option2'] = $result[$v['sku_id']]['options'][1];
}
else {
$result[$v['sku_id']]['option2'] = null;
}
if(isset($result[$v['sku_id']]['options'][2])) {
$result[$v['sku_id']]['option3'] = $result[$v['sku_id']]['options'][2];
}
else {
$result[$v['sku_id']]['option3'] = null;
}
}
return $result;

Categories