Ignore empty strings in array_merge [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have 3 if statements (see code). Each for creating an array of email addresses. How can I merge those 3 strings into a $to (knowing that they could be empty or doesn't even exist)?
Apparently this doesn't work...
if ( in_array('client', $measurement_mail_report_recipients) ) {
$measurement_client_id = intval($_POST['acf']['field_5e147914518a6']);
$list1 = array();
if (have_rows('company_email_addresses', $measurement_client_id)) {
while (have_rows('company_email_addresses', $measurement_client_id)) {
the_row();
$list1[] = get_sub_field('company_email_address');
}
}
}
if ( in_array('contact', $measurement_mail_report_recipients) ) {
$measurement_contact_id = intval($_POST['acf']['field_5e149714d044e']);
$list2 = array();
if (have_rows('contact_email_addresses', $measurement_contact_id)) {
while (have_rows('contact_email_addresses', $measurement_contact_id)) {
the_row();
$list2[] = get_sub_field('contact_email_address');
}
}
}
if ( in_array('extra', $measurement_mail_report_recipients) ) {
$measurement_mail_extra_recipients = $_POST['acf']['field_5f71d4eaaf381'];
if ( $measurement_mail_extra_recipients ) {
$list3 = array();
foreach( $measurement_mail_extra_recipients as $measurement_mail_extra_recipient ) {
$list3[] = $measurement_mail_extra_recipient['field_5f71d55aaf382'];
}
}
}
$to = array_merge($list1, $list2, $list3);

Hopefully this helps you out:
Merge the arrays
Loop through the merged array
Check if current element is "" or null
If so delete it with array_splice()

I know what I forgot. I had to declare the array empty in case the if statement wasn't triggered. Check my working code below:
if ( in_array('client', $measurement_mail_report_recipients) ) {
$measurement_client_id = intval($_POST['acf']['field_5e147914518a6']);
$list1 = array();
if (have_rows('company_email_addresses', $measurement_client_id)) {
while (have_rows('company_email_addresses', $measurement_client_id)) {
the_row();
$list1[] = get_sub_field('company_email_address');
}
}
} else { $list1 = array(); }
if ( in_array('contact', $measurement_mail_report_recipients) ) {
$measurement_contact_id = intval($_POST['acf']['field_5e149714d044e']);
$list2 = array();
if (have_rows('contact_email_addresses', $measurement_contact_id)) {
while (have_rows('contact_email_addresses', $measurement_contact_id)) {
the_row();
$list2[] = get_sub_field('contact_email_address');
}
}
} else { $list2 = array(); }
if ( in_array('extra', $measurement_mail_report_recipients) ) {
$measurement_mail_extra_recipients = $_POST['acf']['field_5f71d4eaaf381'];
if ( $measurement_mail_extra_recipients ) {
$list3 = array();
foreach( $measurement_mail_extra_recipients as $measurement_mail_extra_recipient ) {
$list3[] = $measurement_mail_extra_recipient['field_5f71d55aaf382'];
}
}
} else { $list3 = array(); }
$recipients = array_merge($list1, $list2, $list3);
$to = array_filter($recipients);

$myArray = [];
$myArray2 = [];
// If undefined the value becomes false instead of error (always do this)
$myArray2["value1"] = $_POST["post-value"] ?? false;
// Always use isset to check if a variable is defined
if(isset($myArray["some-value"])){
// do some work
}
// proceed to remove an associated array or any variable
unset($myArray2["value1"]);// You can also unset any variable
PHP isset function returns true if a variable has been defined otherwise false, so use it to check if the array exists. To check if the array has value, use comparison operator like: sth equals another. to delete an associative array or any variable unset it as described above.

//Use this method
$array1 = [0,1,3,6];
$array2 = [];
$array3 = ["a","b","c"];
/*
Store all the collective array in one array
the array_1,2 style will help to resolve things inside for loop
*/
$biggerArray = ["array_1"=>$array1, "array_2"=>$array2, "array_3"=>$array3];
$bigger2 = [];
for($i = 0; $i < 3; $i++){
foreach($biggerArray["$i"] as $k => $v){
if(!$biggerArray["$i"][$k]){
// the value is empty
}else{
// it's not empty
if(!isset($bigger2["array_$i"]){
$bigger2["array_$i"] = [];
}else{
array_push($bigger2["array_$i"],$biggerArray["$i"][$k]);
}
}
}
}
// with function return $bigger2 array

Related

how to remove the curly braces and user_cart string

public function addToCart($id){
$course = Course::findOrfail($id);
$user =Auth::user();
$cart_array = array();
$cart = $user->user_cart;
if ($cart == '') {
array_push($cart_array, array('user_cart' => $course->id));
// print_r($cart_array);
} else {
$founder = false;
$cart_array = json_decode($cart, true);
for ($i = 0; $i < count($cart_array); $i++) {
$cart_for_eacch_course = $cart_array[$i];
if ($cart_for_eacch_course['user_cart'] == $course->id) {
$founder = true;
}
}
if (!$founder) {
array_push($cart_array, array('user_cart' => $course->id));
}
}
$data['user_cart'] = json_encode($cart_array);
$update = User::where('id',$user->id)->update(['user_cart'=> $cart_array]);
Current Output
[{"user_cart":86},{"user_cart":84}]
Expected Output
[84,86]
Now I am having the current Output but I want expected one. I tried by removing the json_encode but it didn't work for me.
You can use array_column() like so
$new_array = array_column($cart_array, 'user_cart');
When you are creating the output array, you are using...
array_push($cart_array, array('user_cart' => $course->id));
which is why you get the sub arrays with the keys. If instead you just add the $course->id values, then this should build the output in the first place rather than having to process it further...
$cart_array[] = $course->id;
You would also need to change the line
if ($cart_for_eacch_course['user_cart'] == $course->id) {
to
if ($cart_for_eacch_course == $course->id) {
as you no longer have the sub index. You could change this part of the code to use in_array() instead which would also be shorter.

Transform a monodimensional PHP array into a multidimensional one

How would you transform a monodimensional array into a multidimensional array in PHP? Suppose you have something like this
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
And you want a function to transform it into
$array['breakfast'] = 'milk';
$array['meal']['firstdish'] = 'pasta';
$array['meal']['seconddish']['maincourse'] = 'veal';
$array['meal']['seconddish']['dressing'] = 'fries';
$array['meal']['dessert'] = 'pie';
The same function should of course transform
$tire['ean'] = '3286347717116';
$tire['brand.maker'] = 'BRIDGESTONE';
$tire['brand.model.name'] = 'POTENZA';
$tire['brand.model.variant'] = 'RE 040 RFT * SZ';
into
$tire['ean'] = '3286347717116';
$tire['brand']['maker'] = 'BRIDGESTONE';
$tire['brand']['model']['name'] = 'POTENZA';
$tire['brand']['model']['variant'] = 'RE 040 RFT * SZ';
I was thinking of using explode, then eval on the results, but eval always feels like cheating to me and I guess it would keep my code from running in HipHop.
The reason I want to do this is that I have to export lots of different tables from a database into XML files, and I already have a robust function that turns a multidimensional array into XML.
Like this:
function build(array &$trg, array $k,$key,$value) {
$p = &$trg;
while ( !empty($k) ) {
$nk = array_shift($k);
if ( !isset($p[$nk]) ) {
$p[$nk] = [];
}
$p = &$p[$nk];
}
$p[$key] = $value;
return $p;
}
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$out = [];
foreach ($array as $key => $value ) {
$path = explode('.',$key);
$last = array_pop($path);
build($out,$path,$last,$value);
}
print_r($out);
You were on the right track with explode, but there's no need to use eval. Once you've got the pieces of the keys available, you can loop over them and incrementally assign a pointer into a new array:
<?php
$array['breakfast'] = 'milk';
$array['meal.firstdish'] = 'pasta';
$array['meal.seconddish.maincourse'] = 'veal';
$array['meal.seconddish.dressing'] = 'fries';
$array['meal.dessert'] = 'pie';
$result = [];
$target = null;
foreach ($array as $key => $value) {
// Start by targeting the base of our resulting array
$target =& $result;
// Break the keys apart into pieces
$keyParts = explode('.', $key);
// Assign new target based on indexing into the result array one "piece" at a time
while ($part = array_shift($keyParts)) {
$target =& $target[$part];
}
// Finally, assign the value to our target
$target = $value;
}
See https://eval.in/625627

Sum up array first, then push into array loop solution

I had a problem with this particular code. The conditions are:
When $rows['Machine#'] is not in array, push in $machineArr array and unset the $totalTimeArr array.
When $rows['Machine#'] is in the array, push $rows['TotalTime'] into $totalTimeArr array for addition.
$graphArr[] should be updated (for array_sum($totalTimeArr)) first before push into array.
only one $graphArr[] for each machine
I now have problems regarding the third condition. It does not calculate first, instead it pushes the first data input. I have tried using do while loop, putting $graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']'; outside the if else loop, but this seems to be the closest I can get to what it's supposed to be. Other codes don't seem to have any problems and work well. Appreciate your recommendations/suggestions/assistance. Below is the code.
while ($rows = mysqli_fetch_array($conn))
{
if(!(in_array($rows['Machine#'], $machineArr)))
{
unset($totalTimeArr);
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
$graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']';
}
else if(in_array($rows['Machine#'], $machineArr))
{
$totalTimeArr[] = $rows['TotalTime'];
}
}
EDIT: I'm currently on this:
while ($rows = mysqli_fetch_array($conn))
{
$exists = false;
if( in_array($rows['Machine#'], $machineArr) )
{
$exists = true;
}
$totalTimeArr[] = $rows['TotalTime'];
if($exists === false)
{
$totalTimeArr = array();
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
}
$graphArr[] = '["'.current($machineArr).'",'.array_sum($totalTimeArr).']';
next($machineArr);
}
The result:
Array ( [0] => ["09CS1", 1.4]
[1] => ["08CS1", 1 ]
[2] => ["06CS1", 1 ]
[3] => ["" , 1.5]
[4] => ["02CS2", 1 ]
[5] => ["01CS2", 20 ]
[6] => ["" , 40 ]
[7] => ["01CS1", 1 ]
)
How do I remove ["", 1.5] and ["", 40]?
Below is the database:
I'm not sure what you need to do, if you need a running sum for a specific type of a machine then do something like:
$totalTileArr = [];
while ($rows = mysqli_fetch_array($conn)) {
if (!isset($totalTileArr[$rows['Machine#']])) {
$totalTileArr[$rows['Machine#']] = [];
}
$totalTimeArr[$rows['Machine#']][] = $rows['TotalTime'];
$graphArr[$rows['Machine#']] = '["' . $rows['Machine#'] . '",' . array_sum($totalTimeArr[$rows['Machine#']]) . ']';
}
A slightly modified version of your code cleaned up
$machineArr = Array();
while ($rows = mysqli_fetch_array($conn)) {
$exists = false;
if( in_array($rows['Machine#'], $machineArr) ) { $exists = true; }
$totalTimeArr[] = $rows['TotalTime'];
if($exists === false) {
unset($totalTimeArr);
$machineArr[] = $rows['Machine#'];
$totalTimeArr[] = $rows['TotalTime'];
$graphArr[] = '["'.$rows['Machine#'].'",'.array_sum($totalTimeArr).']';
}
}
Converted the check into one in_array() search, then comparing using === bitwise operator to evaluate the condition. Also defined $machineArr as an Array() as the first check in your loop would always fail given that $machineArr was (presumably as I don't see the code prior to the while loop) undefined.

Create infinitely deep multidimensional array from string in PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
String with array structure to Array
I have a string "db/yum/user", and I'm trying to explode it so each element of / becomes a deeper dimension.
So the direct method of creating the data variable would be
$config['db']['yum']['user'] = "val";
My attempt so far:
$config = array();
function set_config($key,$value){
global $config;
//Multi deminsional config
$multi_configs = explode('/',$key);
if($multi_configs!==false){
$build_up = array();
$c =& $build_up;
foreach($multi_configs as $multi_config){
$c[$multi_config] = array();
$c =& $c[$multi_config];
}
//$c = $value;
array_merge($config,$c);
return;
}
$config[$key] = $value;
}
set_config('db/yum/user','val');
set_config('db/yum/server','val2');
//etc,etc,etc, this was modified to make more sense in this context.
This is probably what you are looking for:
#!/usr/bin/php
<?php
$config = array();
function set_config($key, $value) {
global $config;
if (FALSE=== ($levels=explode('/',$key)))
return;
$pointer = &$config;
for ($i=0; $i<sizeof($levels); $i++) {
if (!isset($pointer[$levels[$i]]))
$pointer[$levels[$i]]=array();
$pointer=&$pointer[$levels[$i]];
} // for
$pointer=$value;
} // set_config
set_config('db/yum/user','val');
set_config('db/yum/server','val2');
print_r($config);
?>
The output is:
Array
(
[db] => Array
(
[yum] => Array
(
[user] => val
[server] => val2
)
)
)
You can also achieve the same solution using a tree structure in the array . Here is the code to construct the array :
$arr = array (5,6);
$new_arr=array ();
$prev=0;
foreach ($arr as $val) {
$new_arr[$prev] = $val;
$prev=$val;
}
$new_arr[$prev]="value";
Here is the code to retrieve the value:
function retrieve ($arr) {
$prev=0;
while (1) {
if (! isset($arr[$prev] ) )
break;
else $prev = $arr[$prev];
}
return $prev;
}

PHP Multidimensional Array push and loop

I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push.
The idea is to push a "Attribute" and a "Attribute value"
I have tried the formula below
$i = 0;
$array = array();
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[] = ($strAtt => $strVal);
The $array[] = ($strAtt => $strVal); doesnt give me much success.
I have tried array_push($array, $strAtt => $strVal) - no luck..
As an extra questions, how do I loop trough the array and print me multidimensional values ?.
NEW CODE
while ($z->name === 'RECORD')
{
$node = new SimpleXMLElement($z->readOuterXML());
$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[$strAtt] = $strVal;
if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
{
$Print = TRUE;
$Product = $node->PROP[$i]->PVAL;
}
$i++;
}
if($Print == TRUE) {
echo $output;
echo "Product : ".$Product."<br>";
var_dump($array);
}
//print_r($array);
$print = FALSE;
// go to next <product />
$z->next('RECORD');
}
New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?
It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:
$array[$strAtt] = $strVal;
Then to loop the array just do this:
foreach ($array as $key => $value) {
echo "$key = $value\n";
}
Go through array in php , you will understand how array works in php.
Besides if you want to add an element to a multidimensional array you can achieve like this :
$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
$array [$key] = $value;
}
This will be the resulting $array after the loop :
array (
"key1"=> array (
a,b
) ,
"key2"=>
array (c,d)
)
Hope that helps , happy coding :)

Categories