I have a string in the following form:
$my_original_string = "A value1,A value2,E value3,A value4";
The first letter is a sort of label, the value is associated with a label.
I must manipulate and convert my string to the following:
$my_converted_string = "A: value1 value2 value4, E: value3";
With a simple loop, I created an array $temp:
$my_original_string = "A value1,A value2,E value3,A value4";
$original_string_to_array = explode(",", $my_original_string);
$o_len = count($original_string_to_array);
$temp = [];
for($i=0; $i<$o_len; $i++){
$temp[explode(" ",$original_string_to_array[$i])[0]][] = explode(" ",$original_string_to_array[$i])[1];
}
print_r($temp);
/*
Result:
Array
(
[A] => Array
(
[0] => value1
[1] => value2
[2] => value4
)
[E] => Array
(
[0] => value3
)
)
*/
Starting from here, I could eventually loop again to build my new string. Or maybe I could do it even in one loop.
But, is there anything better I could do? I checked the capabilities of array_map, array_filter and array_walk but I could not find a way to apply them in this particular case.
Thanks in advance.
A couple of coding improvements would reduce some of the code, using a foreach instead of the for (where you also have to count the items). Also inside the loop, use explode() once to reduce repetition of the code.
This also inside the loop checks if the key is already present. If it is, it just appends the new value, if it isn't it creates a new value with the key and value. When it outputs the value, it uses implode() to stick the values back together...
$my_original_string = "A value1,A value2,E value3,A value4";
$originalArray = explode(",", $my_original_string);
$output = [];
foreach($originalArray as $item ) {
[$key, $value] = explode(" ", $item, 2);
$output[$key] = (isset($output[$key])) ? $output[$key]." ".$value
: "$key: $value";
}
print_r(implode(", ", $output));
gives...
A: value1 value2 value4, E: value3
Although you can use array_map
$string = "A value1,A value2,E value3,A value4,B value5";
$split = explode(',', $string);
$walk = array();
$map = array_map(function($a) use(&$walk) {
list($key,$value) = explode(' ',$a);
$walk[$key] = (isset($walk[$key]) ?
sprintf('%s %s',$walk[$key],$value)
: sprintf('%s: %s',$key,$value));
return $walk;
}, $split);
$str = implode(',',array_pop($map));
echo $str;
return output with :
A: value1 value2 value4,B: value5,E: value3
or in array
Array
(
[A] => A: value1 value2 value4
[B] => B: value5
[E] => E: value3
)
Note: if you use $map you need to use array_pop to get last element, also you can use $walk if you don't like to use array_pop
Related
I have an array with date & time like below:
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
From each value, the T10:00 should be cut off, so that my new array looks like this:
$new_array = array('2021-05-04', '2021-05-05', '2021-05-06');
How can i do that?
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = [];
foreach($array as $a) {
$a = explode('T', $a)[0];
array_push($new_array, $a);
}
Iterate through the array by array_map with callback function take only first 10 chars, Which represent time.
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = array_map(fn($time)=>substr($time, 0, 10), $array);
print_r($new_array);
Prints:
/*
Array
(
[0] => 2021-05-04
[1] => 2021-05-05
[2] => 2021-05-06
)
*/
the T10:00 should be cut off
If you have a constant time T10:00 and want to get rid of it just replace it with empty!
$array = array('2021-05-04T10:00', '2021-05-05T10:00', '2021-05-06T10:00');
$new_array = array_map(fn($time)=>str_replace('T10:00', '', $time), $array);
print_r($new_array);
//Array ( [0] => 2021-05-04 [1] => 2021-05-05 [2] => 2021-05-06 )
I have a string that looks like this:
"illustration,drawing,printing"
I have an array that looks like this:
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
How can I compare the two and only display the terms that exist in both the string and array?
So in the above example, I would want to output something that looks like this:
SKILLS: illustration, drawing
Thank you!
use explode(), array_intersect() and implode()
<?php
$string = "illustration,drawing,printing";
$array = Array (
0 => 'illustration',
1 => 'drawing',
2 => 'painting',
3 => 'ceramics'
);
$stringArray = explode(',',$string);
$common = array_intersect($stringArray,$array);
echo "Skills :".implode(',',$common);
https://3v4l.org/StqYN
You can do something like this:
Function:
function functionName($string, $array){
$skills = '';
// Create a temp array from your string breaking appart from the commas
$temparr = explode(",", $string);
// Iterate through each of the words now
foreach($temparr as $str){
// Check to see if our current string is in the array provided
if(in_array($str, $array)){
// If it is, then add it to the string "skills"
$skills .= "${str}, ";
}
}
// Cut the last space and comma off the end of the str.
$skills = substr($skills, 0, strlen($skills) - 2);
// Return our results
return 'SKILLS: '.$skills;
}
Usage:
$string = "illustration,drawing,printing";
$array = Array (
0 => "illustration",
1 => "drawing",
2 => "painting",
3 => "ceramics"
);
// Just input our string and the array we want to search through
echo(functionName($string, $array));
Live Demos:
https://ideone.com/qyqgzo
http://sandbox.onlinephpfunctions.com/code/65dc988370ad8ce61ab5ccbc232af4bcf8bd3d42
You could replace the comma , and join the string words on OR | and grep for them. This will match the word anywhere in each array element:
$result = preg_grep("/".str_replace(",", "|", $string)."/", $array);
If you want exact matches only then: "/^(".str_replace(",", "|", $string).")$/"
Firstly convert that string into array.
use array_intersect();
$str = "illustration,drawing,printing";
$ar1 = explode(",",$str);
print_r ($ar1);
$ar2 = Array ("illustration","drawing","painting","ceramics");
echo "<br>";
print_r ($ar2);
$result = array_intersect($ar1, $ar2);
echo "Skills :".implode(',',$result);
OUTPUT:
Array (
[0] => illustration
[1] => drawing
[2] => printing
)
Array (
[0] => illustration
[1] => drawing
[2] => painting
[3] => ceramics
)
SKILLS: illustration, drawing
I've the following variable that is dinamically created:
$var = "'a'=>'123', 'b'=>'456'";
I use it to populate an array:
$array=array($var);
I can't do $array=array('a'=>'123', 'b'=>'456') because $var is always different.
So it shows me:
Array
(
[0] => 'a'=>'123', 'b'=>'456'
)
This is wrong, 'cause I need to get:
Array
(
[a] => 123
[b] => 456
)
What is wrong on my code?
Thanks in advance.
Ideally you should just leverage PHP's syntax to populate an associative array, something like this:
$array = [];
$array['a'] = '123';
$array['b'] = '456';
However, you could actually write a script which parses your input to generate an associate array:
$var = "'a'=>'123', 'b'=>'456'";
preg_match_all ("/'([^']+)'=>'([^']+)'/", $var, $matches);
$array = [];
for ($i=0; $i < count($matches[0]); $i++) {
$array[$matches[1][$i]] = $matches[2][$i];
}
print_r($array);
This prints:
Array
(
[a] => 123
[b] => 456
)
$arrayinput = array("a", "b", "c", "d", "e");
How can I achieve the following output....
output:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => b
[1] => c
)
[2] => Array
(
[0] => c
[1] => d
)
[3] => Array
(
[0] => d
[1] => e
)
[4] => Array
(
[0] => e
)
)
You can use this, live demo here.
<?php
$arrayinput = array("a","b","c","d","e");
$array = [];
foreach($arrayinput as $v)
{
$arr = [];
$arr[] = $v;
if($next = next($arrayinput))
$arr[] = $next;
$array[] = $arr;
}
print_r($array);
live example here: http://sandbox.onlinephpfunctions.com/code/4de9dda457de92abdee6b4aec83b3ccff680334e
$arrayinput = array("a","b","c","d","e");
$result = [];
for ($x = 0; $x < count($arrayinput); $x+=2 ) {
$tmp = [];
$tmp[] = $arrayinput[$x];
if ($x+1 < count($arrayinput)) $tmp[] = $arrayinput[$x+1];
$result[] = $tmp;
}
var_dump($result);
By declaring single-use reference variables, you don't need to call next() -- which is not falsey-safe and there is a warning in the php manual. You also won't need to keep track of the previous index or make iterated calls of count().
For all iterations except for the first one (because there is no previous value), push the current value into the previous subarray as the second element. After pushing the second value, "disconnect" the reference variable so that the same process can be repeated on subsequent iterations. This is how I'd do it in my own project.
Code: (Demo)
$result = [];
foreach (range('a', 'e') as $value) {
if ($result) {
$row[] = $value;
unset($row);
}
$row = [$value];
$result[] = &$row;
}
var_export($result);
If you always want to have 2 elements in each subarray and you want to pad with null on the final iteration, you could use a transposing technique and send a copy of the input array (less the first element) as an additional argument. This is a much more concise technique (one-liner) (Demo)
var_export(array_map(null, $array, array_slice($array, 1)));
I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));