Explode and then merge arrays - php

I have two strings, one containing names separated by commas and the other containing email addresses separated by commas.
I now want my end result to replicate the behaviour as if I had gotten those values from the database with a:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'].'<br />'.$row['email'];
}
So I have for example these strings:
email1#domain.com,email2#domain.com,email3#domain.com
and
name1,name2,name3
And can then explode these into value arrays. Now, after exploding them,
I want to be able to make a loop where in each loop I can get $name[0] and $email[0] together, and $name[1] and $email[1] together, etc.
How can I merge the two arrays (after exploding them) and get the data for each datapair (name and email) in a loop?

So if I understood you right, you are converting your strings (lets call them email, and name) too two arrays (lets call them arrEmail, and arrName) and now you want to get a array with the merged datasets.(creating the arrays should be easy if not check this out: manual for php explode function)
If so I would create a for loop based on the length of your two arrays. In the loop I would extract value i of arrEmail and arrName, and put the information into an two-dimensional array. Maybe something like this:
It should work but I didn't test it for ages so if not leave me a comment.
<?php
$arrEmail = array();
$arrName = array();
$arrGoal;
$arrLength = count($arrName);
//creating two-dimensional Array
for($i = 0; $i < $arrLength; $i++){
$arrGoal[$i] = array($arrName[$i], $arrEmail[$i]);
//should look something like this ((name, email),(name, email)…)
}
$arrGoalLength = count($arrGoal);
//accessing Array
//1. dimension
for($i = 0; $i < $arrGoalLength; $i++){
//2. dimension
//Variables should be global (but aren't)
$newName = $arrGoal[$i][0];
$newEmail = $arrGoal[$i][1];
}
?>

I think you want something like this:
$output = array();
for ($i = 0; $i < count($names); $i++) {
$output[] = $names[$i] . ' ' . $emails[$i];
}
print_R($output);

$emails = 'email1#domain.com,email2#domain.com,email3#domain.com';
$emails = explode(',', $emails);
$names = 'name1,name2,name3';
$names = explode(',', $names);
and you can use array_combine() as follow :
$combined = array_combine($names, $emails);
foreach($combined as $name => $email){
echo $name, ' : ', $email, '<br/>';
}

I think you should use the built in explode function wich will allow you to turn a string to an array by spliting it using a delimiter (comma) :
$names = explode(",",$row['name']);
$email = explode(",",$row['email']);
for merging them you should use something like this
$Array = array();
for ($j = 0; $j < count($names); $j++) {
$Array[] = [$names[$j],$email[$j]];
}

This is kind a related with your question, but only if you like to access the value by a key(e.g. access the name by email provided):
<?php
$emails = 'email1#gmail.com,email2#gmail.com,email3#gmail.com';
$names = 'name1,name2,name3';
$arrayEmails = explode(',',$emails);
$arrayNames = explode(',',$names);
$result = array_combine( $arrayEmails, $arrayNames);
print_r($result);
?>

Related

Print all values of array with a nested index in PHP without a loop

I have an array which has nested String that I want to output without a loop.
Here is the array:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
I want to output this as
First, Second, Third, Forth, Fifth
This is what I tried (but it's in loop)
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
I'd be inclined to break this down into two parts:
Convert the array into a simplified version that just contains the values you want to concatenate. For that, you can use array_map() (https://www.php.net/manual/en/function.array-map.php).
Join the elements of the array without an extra comma on the end. The perfect use case for implode() (https://www.php.net/manual/en/function.implode.php).
Example:
echo implode(', ', array_map(function($item) {
return $item['string_term']->name;
}, $field_my_array));
I am not sure what you're trying to achieve. If you don't want to loop, then you have to manually write like this:
echo $field_my_array[0]['string_term']->name;
echo ", ";
echo $field_my_array[1]['string_term']->name;
...
and so on. Looping is a fundamental programming construct that allows us to automate with a simple count.
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
print $field_my_array[$ctr]['string_term']->name;
if ($ctr < count($field_my_array) -1) {print ", ";}
}
A better one would be this:
$field_my_array[0]['string_term']->name = "First";
$field_my_array[1]['string_term']->name = "Second";
$field_my_array[2]['string_term']->name = "Third";
$field_my_array[3]['string_term']->name = "Forth";
$field_my_array[4]['string_term']->name = "Fifth";
$names = array();
for ($ctr = 0; $ctr < count($field_my_array); $ctr ++) {
$names[] = $field_my_array[$ctr]['string_term']->name;
}
// this creates a string with a comma between items from array
$full_text = implode(', ',$names);
echo $full_text ;
You can use array_merge_recursive with implode
$c = array_merge_recursive(...$field_my_array);
echo implode(',', $c['string_term']['name']);
Live DEMO https://3v4l.org/GdhM5

Mix array with ancestor elements

Seems to be very simple but I'm like, losing a lot of time on this... and no success...
If I have a string:
$str = "She sells seashells"
So I turn every word into an array element
$array = explode(" ", $str);
What I need is, every word receive the ancestor element (if any) and the next ones...
Example result in json format (more easy to show)
"{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}"
Can somebody help?
Thanks!
Really, you can copy a source array for each key, excluding that key:
$str = "She sells seashells";
$array = explode(" ", $str);
$res = [];
for($i = 0; $i < count($array); $i++) {
$res[$array[$i]] = $array;
unset($res[$array[$i]][$i]);
}
print_r($res);
demo
<?php
$str = "She sells seashells";
$arr = explode(" ",$str);
$length = count($arr);
$result = [];
for($i = 0;$i < $length;++$i){
$result[$arr[$i]] = [];
foreach ($arr as $each_val) {
if($each_val === $arr[$i]) continue;
$result[$arr[$i]][] = $each_val;
}
}
echo json_encode($result);
OUTPUT:
{"She":["sells","seashells"],"sells":["She","seashells"],"seashells":["She","sells"]}
Explode the string based on spaces.
Have a result array and make the current iteration value in for loop as the key for it.
Loop again over the array and check if current value matches with outer for loop value. If yes, then continue, else add that value in this result array key.
In the end, json_encode() it and you are done.

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

PHP put several arrays in one separated by ","

I have some arrays extracted from a XML-file. These are in
$array0 = (.......)
$array1 = (.......)
...
$arrayN = (.......)
Now I need a single array with all arrays in it separated by "," as
$masterArray = array($array0,
$array1,
...
$arrayN)
I tried
for ( $i = 0; $i < N; $i++) {
$masterArray = $masterArray + $array[$i];
}
with no result. I tried array_merge but this will give one
$masterArray(......................all items of all $arrays.....)
How can I do it right?
for ( $i = 0; $i < N; $i++) {
$temp = "array".$i;
$masterArray[$i] = ${$temp};
}
Given your exact definition of what you got and what you want the routine should be:
for ( $i = 0; $i < N; $i++) $masterArray[] = ${'array'.$i};
Not much to explain here. You make a new entry in an array with $variable[] = <entry>; and you access your numbered array with a variable variable, see:
http://php.net/manual/en/language.variables.variable.php
I guess you wont to create a multi dimension array:
$masterArray = array();
$masterArray[] = $array0;
$masterArray[] = $array1;
...
$masterArray[] = $arrayN;
this will in all arrays as element of the MasterArray:
$masterArray[0=>(....),1=>(....), ...];
Then access it like this:
$arr1_key1 = $masterArray[1]['key1'] ; //$array1['key1'];
You can add specific keys if you wont:
$masterArray['arr1'] = $array1;
$arr1_key1 = $masterArray['arr1']['key1'] ; //$array1['key1']
In general read some more to get better understanding on how to work with arrays ;)

PHP: Pass dynamically created variables to a built-in function

DESCRIPTION OF PROBLEM:What I am trying to do is pass dynamically created variables from a loop to a function in php. More specifically, I used a for loop to create variables and assign data to them. Then use a for loop to string all the variables together. Then pass the string to the multisort_array function and explode the string to use the variables. I'm not sure what I am doing wrong.
QUESTION:How would I pass a bunch of dynamically created variables to a sort function without knowing how many I am going to create? That is my delema.
CODE:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
// explodes first value of $arr2
$tmp = explode("::",$arr2[0]);
// determines how many dynamic variables to create
for($k=0;$k<count($tmp);$k++){
${"mArr".$k} = Array();
}
// loops thru & assigns all numbers to mArr0
// loops thru & assigns all names to mArr1
for ($k=0;$k<count($arr2);$k++){
$tmp = explode("::",$arr2[$k]);
for($l=0;$l<count($tmp);$l++){
${"mArr".$l}[$k] = $tmp[$l];
}
}
// Will add a for loop to combine the variables into string
$param = "$mArr1,$mArr0";
// send the string to array_multisort to be sorted by name
// have tried the following options:
// 1. array_multisort(explode(",",$param));
// 2. call_user_func_array(array_multisort,explode(",",$param));
// both do not sort & give me an error.
Thank you in advance for your help. I am open to any suggestions on other ways this can be accomplished, but I would like it to be in the php code if at all possible.
Just pass the array itself into the function.
arraySort($array);
Sort the array before splitting it in to other arrays using a custom sorting function:
$arr2[0] = "100::HOMEDEPOT";
$arr2[1] = "200::WALMART";
$arr2[2] = "300::COSTCO";
$arr2[3] = "400::WALGREENS";
$arr2[4] = "500::TACO BELL";
//Split the input in place, you could also use a new array for this
for($i = 0;$i < count($arr2);$i++)
{
$arr2[$i] = explode("::",$arr2[$i]);
}
//Define our new sorting function
function sort_second_item($a,$b)
{
return strcmp($a[1],$b[1]);
}
var_dump($arr2);
usort($arr2,'sort_second_item');
var_dump($arr2);
$rotated = array();
//Rotate $arr2
for($i = 0; $i < count($arr2); $i++)
{
for($j = 0;$j < count($arr2[$i]); $j++)
{
if(!isset($rotated[$j]))
{
$rotated[$j] = array();
}
$rotated[$j][$i] = $arr2[$i][$j];
}
}
var_dump($rotated);

Categories