Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have the following 2 arrays variable.
$a = array("triple","triple","double","single","single");
$b = array("444","555","33","2","3");
i need to convert that 2 arrays to be this array pattern
$array = array(
"triple"=>array("444","555"),
"double"=>array("33"),
"single"=>array("2","3")
);
so that i can get the result like this
triple(444 | 555) double(33) single(2 | 3)
anyone can help me? thanks
Just use array_combine, $b as keys and $a as values, then transfer to a new container grouping them with the key:
$array = array();
foreach(array_combine($b, $a) as $k => $v) {
$array[$v][] = $k;
}
For presentation purposes, just implode them:
foreach($array as $key => $numbers) {
$href = implode('|', $numbers);
$numbers = $key . '(' . implode(' | ', $numbers) . ')' . ' ';
echo "<a href='aaa.php?numbers=$href'>$numbers</a>";
}
You Can use PHP's Array_unique ... Follow this link
And do the following..
$arr = [];
foreach($a as $value) {
if ( $value == 'tripple' ) {
foreach( $b as $val ) if( strlen($val) == 3 ) $arr[$value][] = $val;
}
if ( $value == 'double' ) {
foreach( $b as $val ) if( strlen($val) == 2 ) $arr[$value][] = $val;
}
if ( $value == 'single' ) {
foreach( $b as $val ) if( strlen($val) == 1 ) $arr[$value][] = $val;
}
}
That should work...
If I have the following array $array[0] = array(
"1" => bar,
"2" => foo,
"3" => 13546
); and I implode() it, the value that is returned will be: bar,foo,13546 which cannot be used in a mysql query... How can I place single quotes just to those values that are strings...
I've tryed a couple of ways (like foreach($array as $key=>$value) to check with is_numeric() the $value, and the check is ok but I dont know how to change the value to '$value'...)
Any toughts on this?
EDIT
I found another way to do this for those of you who are interested:
$result[0] = array(
"1" => bar,
"2" => foo,
"3" => 1232.13
);
$copy_r = $result[0];
foreach($copy_r as $key=>$value)
{
if(!is_numeric($value))
{
$insert_array[] = "`$key` = '$value'";
}
else
{
$insert_array[] = "`$key` = $value";
}
}
$final_string = implode(',', $insert_array);
$insert_q = "INSERT INTO `table_name` SET $final_string
ON DUPLICATE KEY UPDATE ($final_string)";
Agree that you should look at prepared statements, however to answer your original question you can do that like this:
$array=array('a', 'b', 'c');
$string = "'" . implode("','", $array) . "'";
Better use prepared queries. But just for funs sake:
implode(',', array_map(function($value) {
if(!is_numeric($value)) {
return '"' . $value . '"';
//adds double quotes, but if you prefer single quotes, use:
//return "'" . $value . "'";
} else {
return $value;
}
}, $array[0]);
The foreach+isnumeric() is probably the best approach. Then to change the value:
$array[$key] = "'" . $value . "'";
which turns foo/"foo" into 'foo'/"'foo'" and so on.
If you use the mysql-driver:
function escape( $x ) {
return "'" . mysql_real_escape_string($x) . "'";
}
$data = array( "1" => bar, "2" => foo, "3" => 13546 );
echo implode( ',', array_map('escape', $data) );
The verified solution didn't work for me. Must be something that i'm doing incorrectly, but the below solution worked for me and i used the result in my MYSQL IN clause since all the values needs to be in quoted form in that query.
The solution is simple and it uses call by reference to modify the original array values and array filter of PHP to loop through all the values.
function quote(&$a){
$a='"'.$a.'"';
}
$arr= array('car','bus','truck','bike');
array_filter( $arr,'quote');
echo implode(',', $arr);
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.