I have string like this
$string = 'title,id,user(name,email)';
and I want result to be like this
Array
(
[0] => title
[1] => id
[user] => Array
(
[0] => name
[1] => email
)
)
so far I tried with explode function and multiple for loop the code getting ugly and i think there must be better solution by using regular expression like preg_split.
Replace the comma with ### of nested dataset then explode by a comma. Then make an iteration on the array to split nested dataset to an array. Example:
$string = 'user(name,email),office(title),title,id';
$string = preg_replace_callback("|\(([a-z,]+)\)|i", function($s) {
return str_replace(",", "###", $s[0]);
}, $string);
$data = explode(',', $string);
$data = array_reduce($data, function($old, $new) {
preg_match('/(.+)\((.+)\)/', $new, $m);
if(isset($m[1], $m[2]))
{
return $old + [$m[1] => explode('###', $m[2])];
}
return array_merge($old , [$new]);
}, []);
print '<pre>';
print_r($data);
First thanks #janie for enlighten me, I've busied for while and since yesterday I've learnt a bit regular expression and try to modify #janie answer to suite with my need, here are my code.
$string = 'user(name,email),title,id,office(title),user(name,email),title';
$commaBetweenParentheses = "|,(?=[^\(]*\))|";
$string = preg_replace($commaBetweenParentheses, '###', $string);
$array = explode(',', $string);
$stringFollowedByParentheses = '|(.+)\((.+)\)|';
$final = array();
foreach ($array as $value) {
preg_match($stringFollowedByParentheses, $value, $result);
if(!empty($result))
{
$final[$result[1]] = explode('###', $result[2]);
}
if(empty($result) && !in_array($value, $final)){
$final[] = $value;
}
}
echo "<pre>";
print_r($final);
With PHP if you have a string which may or may not have spaces after the dot, such as:
"1. one 2.too 3. free 4. for 5.five "
What function can you use to create an array as follows:
array(1 => "one", 2 => "too", 3 => "free", 4 => "for", 5 => "five")
with the key being the list item number (e.g the array above has no 0)
I presume a regular expression is needed and perhaps use of preg_split or similar? I'm terrible at regular expressions so any help would be greatly appreciated.
What about:
$str = "1. one 2.too 3. free 4. for 5.five ";
$arr = preg_split('/\d+\./', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($arr);
I got a quick hack and it seems to be working fine for me
$string = "1. one 2.too 3. free 4. for 5.five ";
$text_only = preg_replace("/[^A-Z,a-z]/",".",$string);
$num_only = preg_replace("/[^0-9]/",".",$string);
$explode_nums = explode('.',$num_only);
$explode_text = explode('.',$text_only);
foreach($explode_text as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$text_array[] = $value;
}
}
foreach($explode_nums as $key => $value)
{
if($value !== '' && $value !== ' ')
{
$num_array[] = $value;
}
}
foreach($num_array as $key => $value)
{
$new_array[$value] = $text_array[$key];
}
print_r($new_array);
Test it out and let me know if works fine
Without foreach,
how can I turn an array like this
array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");
to a string like this
item1='object1', item2='object2',.... item-n='object-n'
I thought about implode() already, but it doesn't implode the key with it.
If foreach it necessary, is it possible to not nest the foreach?
EDIT: I've changed the string
EDIT2/UPDATE:
This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use ternary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it is concise or not doesn't matter that much.
In this case: putting the foreach in a function will be much more readable and modular than writing a one-liner(Even though all the answers are great!).
You could use http_build_query, like this:
<?php
$a=array("item1"=>"object1", "item2"=>"object2");
echo http_build_query($a,'',', ');
?>
Output:
item1=object1, item2=object2
Demo
and another way:
$input = array(
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n'
);
$output = implode(', ', array_map(
function ($v, $k) {
if(is_array($v)){
return $k.'[]='.implode('&'.$k.'[]=', $v);
}else{
return $k.'='.$v;
}
},
$input,
array_keys($input)
));
or:
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
I spent measurements (100000 iterations), what fastest way to glue an associative array?
Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"
We have array (for example):
$array = [
'test0' => 344,
'test1' => 235,
'test2' => 876,
...
];
Test number one:
Use http_build_query and str_replace:
str_replace('=', ':', http_build_query($array, null, ','));
Average time to implode 1000 elements: 0.00012930955084904
Test number two:
Use array_map and implode:
implode(',', array_map(
function ($v, $k) {
return $k.':'.$v;
},
$array,
array_keys($array)
));
Average time to implode 1000 elements: 0.0004890081976675
Test number three:
Use array_walk and implode:
array_walk($array,
function (&$v, $k) {
$v = $k.':'.$v;
}
);
implode(',', $array);
Average time to implode 1000 elements: 0.0003874126245348
Test number four:
Use foreach:
$str = '';
foreach($array as $key=>$item) {
$str .= $key.':'.$item.',';
}
rtrim($str, ',');
Average time to implode 1000 elements: 0.00026632803902445
I can conclude that the best way to glue the array - use http_build_query and str_replace
I would use serialize() or json_encode().
While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
Using array_walk
$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");
$r=array();
array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));
echo implode(', ', $r);
IDEONE
You could use PHP's array_reduce as well,
$a = ['Name' => 'Last Name'];
function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}
$imploded = array_reduce(array_keys($a), "acc");
Change
- return substr($result, (-1 * strlen($glue)));
+ return substr($result, 0, -1 * strlen($glue));
if you want to resive the entire String without the last $glue
function key_implode(&$array, $glue) {
$result = "";
foreach ($array as $key => $value) {
$result .= $key . "=" . $value . $glue;
}
return substr($result, (-1 * strlen($glue)));
}
And the usage:
$str = key_implode($yourArray, ",");
For debugging purposes. Recursive write an array of nested arrays to a string.
Used foreach. Function stores National Language characters.
function q($input)
{
$glue = ', ';
$function = function ($v, $k) use (&$function, $glue) {
if (is_array($v)) {
$arr = [];
foreach ($v as $key => $value) {
$arr[] = $function($value, $key);
}
$result = "{" . implode($glue, $arr) . "}";
} else {
$result = sprintf("%s=\"%s\"", $k, var_export($v, true));
}
return $result;
};
return implode($glue, array_map($function, $input, array_keys($input))) . "\n";
}
Here is a simple example, using class:
$input = array(
'element1' => 'value1',
'element2' => 'value2',
'element3' => 'value3'
);
echo FlatData::flatArray($input,', ', '=');
class FlatData
{
public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')
{
$output = implode($separator_elements, array_map(
function ($v, $k, $s) {
return sprintf("%s{$s}%s", $k, $v);
},
$input,
array_keys($input),
array_fill(0, count($input), $separator)
));
return $output;
}
}
For create mysql where conditions from array
$sWheres = array('item1' => 'object1',
'item2' => 'object2',
'item3' => 1,
'item4' => array(4,5),
'item5' => array('object3','object4'));
$sWhere = '';
if(!empty($sWheres)){
$sWhereConditions = array();
foreach ($sWheres as $key => $value){
if(!empty($value)){
if(is_array($value)){
$value = array_filter($value); // For remove blank values from array
if(!empty($value)){
array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'
$sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));
}
}else{
$sWhereConditions[] = sprintf("%s='%s'", $key, $value);
}
}
}
if(!empty($sWhereConditions)){
$sWhere .= "(".implode(' AND ', $sWhereConditions).")";
}
}
echo $sWhere; // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))
Short one:
$string = implode('; ', array_map(fn($k, $v) => "$k=$v", array_keys($array), $array));
Using explode to get an array from any string is always OK, because array is an always in standard structure.
But about array to string, is there any reason to use predefined string in codes? while the string SHOULD be in any format to use!
The good point of foreach is that you can create the string AS YOU NEED IT!
I'd suggest still using foreach quiet readable and clean.
$list = array('a'=>'1', 'b'=>'2', 'c'=>'3');
$sql_val = array();
foreach ($list as $key => $value) {
$sql_val[] = "(" . $key . ", '" . $value . "') ";
}
$sql_val = implode(', ', $sql_val);
with results:
(a, '1') , (b, '2') , (c, '3')
|
(a: '1') , (b: '2') , (c: '3')
|
a:'1' , b:'2' , c:'3'
etc.
Also if the question is outdated and the solution not requested anymore, I just found myself in the need of printing an array for debugging purposes (throwing an exception and showing the array that caused the problem).
For this reason, I anyway propose my simple solution (one line, like originally asked):
$array = ['a very' => ['complex' => 'array']];
$imploded = var_export($array, true);
This will return the exported var instead of directly printing it on the screen and the var $imploded will contain the full export.
looking for the code can remove characters from the array and display numbers only.
array(
1=>123456 hello; / &,
2=>128767 ^% * ! ajsdb,
3=>765678 </ hello echo.,
);
i want to remove the floowing from the array
hello; / &
^% * ! ajsdb
</ hello echo.
and wants to keep as stated
array(
1=>123456,
2=>128767,
3=>765678,
);
Thanks and Kind Regards,
You want to use preg_replace to replace all non-numeric chars with ''
$arr = array(
1 => "1234 perr & *",
2 => "3456 hsdsd 3434"
);
foreach($arr as &$item) {
$item = preg_replace('/\D/', '', $item);
}
var_dump($arr);
results in
array(2) { [1]=> string(4) "1234" [2]=> &string(8) "34563434" }
Make a for statement to get values of your array and try this:
foreach($arr as $value){
$cleansedstring = remove_non_numeric($value);
echo $cleansedstring;
}
function remove_non_numeric($string) {
return preg_replace('/\D/', '', $string)
}
<?php
// Set array
$array = array(
1 => "123456 hello; / &",
2 => "128767 ^% * ! ajsdb",
3 => "765678 </ hello echo.",
);
// Loop through $array
foreach($array as $key => $item){
// Set $array[$key] to value of $item with non-numeric values removed
// (Setting $item will not change $array, so $array[$key] is set instead)
$array[$key] = preg_replace('/[^0-9]+/', '', $item);
}
// Check results
print_r($array);
?>
function number_only($str){
$slength = strlen($str);
$returnVal = null;
for($i=0;$i<$slength;$i++){
if(is_numeric($str[$i])){
$returnVal .=$str[$i];
}
}
return $returnVal;
}
You should use preg_replace using [0-9]+
like this
$values = array(
1=>"123456 hello; / &",
2=>"128767 ^% * ! ajsdb",
3=>"765678 </ hello echo",
);
$number_values = array();
foreach($values as $value) {
$pieces = explode(' ', $value);
$numbers = array_filter($pieces, function($value) {
return is_numeric($value);
});
if(count($numbers) > 0)
{
$number_values[] = current($numbers);
}
}
print_r($number_values);
I would advice you to take a look at the intval method (http://php.net/manual/en/function.intval.php) and the foreach loop (http://php.net/manual/en/control-structures.foreach.php).
With those 2 functions combined you will be able to clear all the elements from the not numeric characters,
Why not array_walk() ? http://php.net/manual/en/function.array-walk.php
$arr = array(
1 => "1234 perr & *",
2 => "3456 hsdsd 3434"
);
array_walk($arr, function(&$item) {
$item = preg_replace('/\D/', '', $item);
});
print_r($arr);
Result:
Array
(
[1] => 1234
[2] => 34563434
)
Check it online:
http://sandbox.onlinephpfunctions.com/code/d63d07e58f9ed6984f96eb0075955c7b36509f81
I've got an array called $myarray with values like these:
myarray = array (
[0] => eat-breakfast
[1] => have-a-break
[2] => dance-tonight
[3] => sing-a-song
)
My goal is to search for a part of this array and get the rest of it. Here is an example:
If i submit eat, I would like to get breakfast.
If i submit have, I would like to get a-break.
I just try but I'm not sure at all how to do it...
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
It displays:
eat-breakfastArray ( )
But I want something like that:
breakfast
I think I'm totally wrong, but I don't have any idea how to proceed.
Thanks.
use
stripos($word, $myarray)
<?php
$myarray = array (
'eat-breakfast',
'have-a-break',
'dance-tonight',
'sing-a-song'
) ;
function search($myarray, $word){
foreach($myarray as $index => $value){
if (stripos($value, $word) !== false){
echo str_replace(array($word,'-'), "", $value);
}
}
}
search($myarray, 'dance');
echo "<br />";
search($myarray, 'have-a');
echo "<br />";
search($myarray, 'sing-a');
demo
I think the word you seek is at the beginning. Try this
function f($myarray, $word)
{
$len = strlen($word);
foreach($myarray as $item)
{
if(substr($item, 0, $len) == $word)
return substr($item, $len+1);
}
return false;
}
You're feeding the wrong information into preg_match, although I'd recommend using array_search().. Check out my updated snippet:
$word = 'eat';
$pattern = '/'.$word.'/i';
foreach ($myarray as $key => $value) {
if(preg_match($pattern, $value, $matches)){
echo $value;
}
}
print_r($matches);
To get rid of that last bit, just perform a str_replace operation to replace the word with ""
This will both search the array (with a native function) and return the remainder of the string.
function returnOther($search, $array) {
$found_key = array_search($search, $array);
$new_string = str_replace($search . "-", "", $array[$found_key]);
return $new_string;
}