Explode/Implode in foreach loop - php

I have a list of strings like
$list = "foo, bar";
I use explode on this list to get the list items as an array:
$strings = explode(", ", $list);
Now I need to take each item of the array and pass it to an API one by one and the API will return the IDs for the list entries. I want to end up with a string that is just like $list but with the IDs instead of the strings.
My problem is that I can't pass an array to the API funtion. I need to do it for every single list item. So I'm looping through the array:
foreach($strings as $names){
$ID = $o_api->GetGroupIdsByName($s_token, $names)->getData();
$AssignedGroups = implode("", $ID).";";
echo $AssignedGroups;
}
If I run this code the result is: 3;4;
Which is exactly what I need to pass it to another API function. But when I need to re-use this list outside of the loop . If I then use $AssignedGroups I only get the last ID, not the 2 (or more) merged ones.
What am I doing wrong?
Here is the complete code for reference:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
foreach($Groups as $Names){
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
$AssignedGroups = implode("", $GroupIDs).";";
echo $AssignedGroups;
}
$o_api->CreateUser($s_token, $Login, $Password, $IsOfflineUser, $IsWindowsUser, $FirstName, $LastName, $AssignedGroups, $Ratings);

What really should be done here:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
// init as empty array
$AssignedGroups = [];
foreach ($Groups as $Names) {
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
// a new string to array
$AssignedGroups[] = implode(';', $GroupIDs);
}
// here you can implode again:
$AssignedGroups = implode(';', $AssignedGroups);
// or even with another delimiter
$AssignedGroups = implode(',', $AssignedGroups);
Fiddle with implode example.

Related

Order array of strings based on a portion of each string

How can i order an array from this:
$unordered_array = array('11196311|3','17699636|13','11196111|0','156875|2','17699679|6','11196237|7','3464760|10');
To this
$ordered_array = array('11196111', '156875', '11196311', '17699679','11196237','3464760', '17699636');
The number after the "|" defines the position, and the array needs to be ordered from lower to higher, and remove the position number in the final array.
Why you don't try by yourself ? You take more writing your answer than doing it by yourself.
$array = array();
foreach($unordered_array as $value) {
$value = explode('|', $value);
$array [$value[1]]= $value[0];
}
ksort($array);
$ordered_array = array_values($array);
var_dump($ordered_array);

How to merge multiple arrays in array without duplicates

I am a newbie in this and I have read lots of stuff about this matter (including some topics here), before starting this topic, but I do not quite get it yet, so I will ask for some help (if it is possible) :)
So, in the column that I want to print I have values like this on every row:
value1|value2|value5|value12|value25
value3|value5|value12|value14|value26|value32|value55
value1|value2|value14|value26|value31
The number of rows can be 3 or 1500+... So I want to merge the arrays and print those values sorted and without duplicates: value1, value2, value3, value5, value12, etc...
I have tried to explode the arrays, but I could not find out how to assign a variable to every array and merge them and all I have done is to print all values:
foreach ($rows as $areas) {
foreach (explode('|', $areas->value) as $area) {
var_dump($area);
}
}
Afterwards I have read somewhere this will be very slow if I have many rows (and I am going to have thousands), so I am stuck here and I do not know what else I could do...
I will appreciate any help and direction that you can give me, because it is too hard for me and I can not do it without help
Thank you in advance
You can store each value of your exploded string as key (if it's not an object nor array), it store only unique values. Then you have to just use array_keys() to get keys and sort returned array:
$rows = array(
'value1|value2|value5|value12|value25',
'value3|value5|value12|value14|value26|value32|value55',
'value1|value2|value14|value26|value31'
);
$results = array();
foreach ($rows as $row) {
$items = explode('|', $row);
foreach ($items as $item) {
$results[$item] = 0;
}
}
$results = array_keys($results);
sort($results, SORT_NATURAL);
Live demo on eval.in
There are two ways of doing this:
<?php
$str = 'value1|value2|value5|value12|value25';
$str1 = 'value3|value5|value12|value14|value26|value32|value55';
$str2 = 'value1|value2|value14|value26|value31';
//-- Method 1: Concat and make a single string and then explode and make a single array
$finalString = $str . '|' . $str1 . '|' . $str2;
print_r(array_unique(explode('|', $finalString)));
//-- Method 2: explode first and then merge into a single array
$strArr = explode('|', $str);
$strArr1 = explode('|', $str1);
$strArr2 = explode('|', $str2);
print_r(array_unique(array_merge($strArr, $strArr1, $strArr2)));

Explode and make array for every value

I've tried to make this:
phones:[{"numbers":12345},{"numbers":67890}]
How can I achieve that from an explode?
$phones = "123456;7890
$phones = explode(';', $phones);
I've tried using foreach like this:
foreach($phones as $phone){
$array["numbers"] = $phone;
}
But it keep replacing the first key. and yes i read that PHP array can't have the same key on an array.
The problem is that you're setting the 'numbers' key in the array on each iteration. Instead, you want the result to be an array where every element is an associative array where the key is 'numbers' and the value is a number:
$phones = "123456;7890";
$exploded = explode(';', $phones);
$result = array();
foreach ($exploded as $elem) {
$result[] = array('numbers' => $elem);
}

How to group numbers in an array in php

I have a loads of numbers in a string
$userlist = '12,17,46,35,32,66,43,64'; //the userlist can be as long as i want
$arr2 = explode(',', $userlist);
i dont now how to get them to output like the follow.
12,17
46,35
32,66
43,64
Thank You for taking the time to read.
You can use array_chunk to group two together again and then iterate over the groups and implode each again with the ,. Example (Demo):
$userPairings = array_chunk($arr2, 2);
foreach ($userPairings as &$pair)
{
$pair = implode(',', $pair);
}
unset($pair);
echo implode("\n\n", $userPairings);
Output:
12,17
46,35
32,66
43,64

How to create a string that contains the keys of a given array in PHP?

I have an array holding this data:
Array (
[1402377] => 7
[1562441] => 7
[1639491] => 9
[1256074] => 10
)
How can create a string that contains the keys of the above array?
Essentially, I need to create a comma separated string that consists of an array's keys
The string would look like: 'key','key','key'
Do I need to create a new array consisting of the keys from an existing array?
The reason I need to do this is because I will be querying a MySQL database using a WHERE in () statement. I would rather not have to query the database using a foreach statement. Am I approaching this problem correctly?
I've tried using a while statement, and I'm able to print the array keys that I need, but I need those keys to be an array in order to send to my model.
The code that allowed me to print the array keys looks like this:
while($element = current($array)) {
$x = key($array)."\n";
echo $x;
next($array);
}
$string = implode(',', array_keys($array));
By the way, for looping over an array consider not using current and next but use foreach:
foreach ($array as $key => $value) {
//do something
}
This will automatically iterate over the array until all records have been visited (or not at all if there are no records.
$keys = array_keys($array);
$string = implode(' ',$keys);
In your case, were you are using the result in a IN clause you should do:
$string = implode(',', $keys);
$yourString = '';
foreach($yourArr as $key => $val) {
$yourString .=$key.",";
}
echo rtrim($yourString, ",");
//OR
$yourString = implode(",", array_keys($yourArray));
See : array_keys
implode(', ', array_keys($array));
Use php array_keys and implode methods
print implode(PHP_EOL, array_keys($element))
The string would look like: 'key','key','key'
$string = '\'' . implode('\',\'', array_keys($array)) . '\'';
Imploding the arguments and interpolating the result into the query can cause an injection vulnerability. Instead, create a prepared statement by repeating a string of parameter placeholders.
$paramList = '(' . str_repeat('?, ', count($array) - 1) . '?)'
$args = array_keys($array);
$statement = 'SELECT ... WHERE column IN ' . $paramList;
$query = $db->prepare($statement);
$query->execute($args);

Categories