I have a multidimensional array. Like this.
Array
(
[38] => Array
(
[quantity] => 1
[price] => 149
[product_code] => 4578425
)
[39] => Array
(
[quantity] => 2
[price] => 300
[product_code] => 4578426
)
)
I want to create query string from these values like
https://www.domain.com/checkout.php?PRODS=4578425,4578426&QTY=1,2&CART=1
Without using loops...
I don't think AFAIK, it is possible, since you have arrays in array, so using implode won't help. But, using loops, yea.
Use this code:
$prods = array();
$qty = array();
foreach ($array as $item)
{
$prods[] = $item["product_code"];
$qty[] = $item["quantity"];
}
echo 'https://www.domain.com/checkout.php?PRODS=', implode(',', $prods),'&QTY=', implode(',', $qty),'&CART=1';
you can use implode() method
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
Yes i think there is a way,
You can use serialize to put it in a string and then unserialize to get it back to an array like this:
<?php
$arr = Array
(
38 => Array
(
'quantity' => 1,
'price' => 149,
'product_code' => 4578425
),
39 => Array
(
'quantity' => 2,
'price' => 300,
'product_code' => 4578426
)
);
$newarr = 'https://www.domain.com/checkout.php?string=';
$newarr .= serialize($arr);
?>
then you have this result:
https://www.domain.com/checkout.php?string=a:2:{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}a:2:{i:38;a:3:{s:8:"quantity";i:1;s:5:"price";i:149;s:12:"product_code";i:4578425;}i:39;a:3:{s:8:"quantity";i:2;s:5:"price";i:300;s:12:"product_code";i:4578426;}}
No loops but it is not pretty!!!
If you wish to use this inside url I have to warn you. The url get method is only intended for short information like id's or other key values. If your url gets over 2000 characters most web-servers would have problems with it. Not sure if that was your intention.
Related
hey i have array with returned keys
$temp = $sth->fetchAll(PDO::FETCH_ASSOC);
my result looks like this:
[0] => [
'id' = 11,
'title' => 't1'
]
[1] => [
'id' = 12,
'title' => 't2'
]
if i want to return ids as key i call something like this:
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
and my resoult looks like this:
[11] => [
'title' => 't1'
]
[12] => [
'title' => 't2'
]
how to return array of objects by ID? when i do this i dont have methods in object...
$temp = array_map(function($v){return $v[0];}, $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_CLASS));
I will do a bit easier code like below:-
$fianl_array = array_combine(array_column($temp,'id'),$temp);
Output:- https://eval.in/993728
Reference:-
array_column()
array_combine()
Using foreach:
foreach($input as $k=>$v){
$output[$v['id']] = array('title'=>$v['title']);
}
print_r($output);
Just had to add this as an answer as I believe it's the shortest way of doing this, using array_column() with a third parameter which is the key you want the data indexed by. If you use null as the second parameter, it will index all the data by 'id', you could instead use 'title' and this will only index the title columns by ID...
$output = array_column($temp,null,'id');
Which gives...
Array
(
[11] => Array
(
[id] => 11
[title] => t1
)
[12] => Array
(
[id] => 12
[title] => t2
)
)
I have an arrays like follows:
Array
(
[option] => nos
[optioncost] => 10
)
Array
(
[option] => opts
[optioncost] => 20
)
Array
(
[option] => opts
[optioncost] => 30
)
need to convert this as like the following json format
[{"option":nos,"optioncost":10},{"option":opts,"optioncost":20},{"option":optse,"optioncost":30}]
Try this code :
<?php
$arr = array();
$arr[] = array('option' => 'nos',
'optioncost' => 10
);
$arr[] = array('option' => 'opts',
'optioncost' => 20
);
$arr[] = array('option' => 'optse',
'optioncost' => 30
);
echo json_encode($arr);
?>
Output :
[{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
Hope this helps !
The json example you've provided isn't valid because strings aren't quoted (nos / opts), something you could have easily tested on any online json validator.
You'll need to construct proper arrays - where strings are "quoted" - and use the json_encode() function, i.e.:
$arr1 = ['option' => "nos", 'optioncost' => 10];
$arr2 = ['option' => "opts", 'optioncost' => 20];
$arr3 = ['option' => "opts", 'optioncost' => 30];
echo json_encode([$arr1, $arr2, $arr3]);
# [{"option":"nos","optioncost":10},{"option":"opts","optioncost":20},{"option":"opts","optioncost":30}]
DEMO
Note:
Strings need to be quoted, but floats, ints or bools don't.
I need to convert my array but I don't have extended experience to complete this task.
Please help me to find a way to do please?
I have this:
Array(
[0] => Array
(
[BTC] => 0.07634
)
[1] => Array
(
[ETH] => 0.00103
)
[2] => Array
(
[LTC] => 0.006787
)
[3] => Array
(
[XMR] => 0.006351
)
And I need this:
Array(
[BTC] => 0.07634
[ETH] => 0.00103(
[LTC] => 0.006787
[XMR] => 0.006351
[ZEC] => 0.00144
[MD_DT_CAD] => 2017-08-14 02:16:44
)
You have following
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
You can achieve your result by following.
<?php
$data =array(
array("BTC" => 0.07634),
array("ETH" => 0.00103),
array("LTC" => 0.006787),
array("XMR" => 0.006351)
);
foreach($data as $value){
foreach ($value as $key => $value1) {
$new_arr[$key] = $value1;
}
}
echo "<pre>";
print_r($new_arr);
?>
Simple use call_user_func_array with array_merge
$array = Array("0" => Array("BTC" => 0.07634),"1" => Array("ETH" => 0.00103),"2" => Array("LTC" => 0.006787),"3" => Array("XMR" => 0.006351));
$new_array = call_user_func_array('array_merge', $array);
print_r($new_array);
<?php $array=array(array("BTC" => 0.07634),array("ETH" => 0.00103),array("LTC" => 0.006787),
array("XMR" => 0.006351));
//echo print_r($array);
$array2 = array_reduce($array, 'array_merge', array());//or call_user_func_array('array_merge', $array);
echo print_r($array2);
?>
Assuming your array is called $array :
$new_array = array_merge(... $array);
Explaination : array_merge() takes an undefined amount of different arrays as parameters, gathers them as entries in a single array by using the splat operator (...) and then merges all these arrays in one before returning it.
Calling that function and passing it a single array and using the splat operator in the calling too makes that single array to be the single array containing the arrays to merge on which the function will work. By doing that, you can have the function to merge sub_arrays of an array you already have without calling additional functions.
I have the following problem:
I have an php array looking like this:
$array = [
[
['sales_count' => '2'],
['customer_id' => '1'],
],
[
['sales_count' => '3'],
['customer_id' => '2'],
]
];
Now if I use json_encode on this array, I get the following result:
[[{"sales_count":"2"},{"customer_id":"1"}],[{"sales_count":"3"},{"customer_id":"2"}]]
However, I'm trying to get the following output: (an array of flat, associative arrays)
[{"sales_count":"2","customer_id":"1"},{"sales_count":"3","customer_id":"2"}]
This is because of the fact that there are two arrays inside your original array on indexes 0 and 1
You need to do something like this
$masterArray = Array (
[0] => Array (
[0] => Array ( [sales_count] => 2 )
[1] => Array ( [customer_id] => 1 )
)
[1] => Array (
[0] => Array ( [sales_count] => 3 )
[1] => Array ( [customer_id] => 2 )
)
);
$json_array = array_merge($masterArray[0], $masterArray[1]);
echo json_encode($json_array);
Syntax for the $masterArray maybe wrong but follow the concept.
on your array should be:
$data = array(
array("sales_count" => 2),
array("customer_id" => 1),
array("sales_count" => 2),
array("customer_id" => 1),
);
json_encode($data);
for you to achieve your expected output.
though if your array is correct you can access your json object by
var data = [
[
{"sales_count":"2"},
{"customer_id":"1"}
],
[
{"sales_count":"3"},
{"customer_id":"2"}
]
];
data[0][0].sales_count will access sales_count = 2 on your 1st array.
I come from VietNam. My English does not good. So, I write this code. I hope this help you.
$arr = array(
0 => array(0 => array('sales_count'=>2),1 => array('customer_id' => 1)),
1 => array(0 => array('sales_count'=>3),1 => array('customer_id' => 2)),
);
$new_arr = array();
foreach($arr as $key => $value){
foreach($value as $kvalue => $vvalue){
$new_arr[] = $vvalue;
}
}
print_r(json_encode($new_arr));
Well, you could restructure them and put them inside a new one. Example:
$new_array = array();
array_walk_recursive($array, function($val, $key) use (&$new_array) {
$new_array[] = array($key => $val);
});
$new_array = json_encode($new_array);
echo '<pre>';
print_r($new_array);
// [{"sales_count":2},{"customer_id":1},{"sales_count":3},{"customer_id":2}]
Or just a simple loop, just simply, push them inside:
$new_array = array();
foreach($array as $values) {
foreach($values as $val) {
$new_array[] = $val;
}
}
echo json_encode($new_array);
Sample output as above.
To flatten the deep associative data in each "row", none of the previous answers work as required. Other techniques provided merely flatten the data to become an array of single-element associative rows (or worse destroy associative relationships while flattening). For the record, dynamically flattening an array's first level is more succinctly coded as array_merge(...$array).
Instead, you must iterate all rows and specifically merge their subarrays. This will flatten the deep structure only so that rows now have two associative elements. THIS is what the question is actually asking for.
Code: (Demo)
echo json_encode(
array_map(
fn($a) => array_merge(...$a),
$array
)
);
I would like to turn the following string into an array:
prijs=0,209&orderby=price&order=undefined&posts_per_page=undefined
INTO
array(
[prijs] => Array
(
[0] => 0
[1] => 209
)
[orderby] => Array
(
[0] => price
)
[order] => Array
(
[0] => undefined
)
[posts_per_page] => Array
(
[0] => undefined
)
)
Something like that. Is that possible?
Now I'm using some foreach loops, but that's not so fast and ideal like a RegEx.
It's a script which needs to load as fast as possible, so every bit of improvement in the code may help.
The amount of arrays can be variable. But it will always be 2 levels deep, like above. And just one main array.
You don't need REGEX for this. The string you have shown looks like a URL query string, in which case $_GET will already hold the values you need:-
var_dump($_GET);
Should give you:-
array (size=4)
'prijs' => string '0,209' (length=5)
'orderby' => string 'price' (length=5)
'order' => string 'undefined' (length=9)
'posts_per_page' => string 'undefined' (length=9)
Otherwise you can use parse_string().
$values = array();
parse_str('prijs=0,209&orderby=price&order=undefined&posts_per_page=undefined', $values);
var_dump($values);
Output:
array (size=4)
'prijs' => string '0,209' (length=5)
'orderby' => string 'price' (length=5)
'order' => string 'undefined' (length=9)
'posts_per_page' => string 'undefined' (length=9)
Looks like you're in need of array_walk as it should be faster than a foreach even if it does pretty much the same thing it does it at a lower level.
as vascowhite suggested you can use $_GET if you have it or parse_str() to get an initial array, after that:
array_walk($array, function(&$n) {
$n = explode(',', $n);
});
Live code: http://3v4l.org/YfuKs
Results in exactly what you want (always having arrays instead of CSV strings):
Array
(
[prijs] => Array
(
[0] => 0
[1] => 209
)
[orderby] => Array
(
[0] => price
)
[order] => Array
(
[0] => undefined
)
[posts_per_page] => Array
(
[0] => undefined
)
)
PS: instead of explode() you can use preg_split('/,/', $n) since you mentioned RegEx and see which one is faster for you
$str = 'prijs=0,209&orderby=price&order=undefined&posts_per_page=undefined';
$array = preg_split('/[&]/' , $str);
foreach ($array as $a)
{
$a = preg_split('/[=]/' , $a);
$a[1] = preg_split('/[,]/' , $a[1]);
}
var_dump($array);
Well, you can use something like this:
<?php
parse_str("prijs=0,209&orderby=price&order=undefined&posts_per_page=undefined",$myArray);
$myArray['prijs'] = explode(",", $myArray['prijs']);
$myArray['orderby'] = explode(",", $myArray['orderby']);
$myArray['order'] = explode(",", $myArray['order']);
$myArray['posts_per_page'] = explode(",", $myArray['posts_per_page']);
print_r($myArray);
?>
function urlSplitter($input)
{
$step1Array = explode('&', $input);
$result = array();
foreach($step1Array as $element)
{
$parts = explode("=", $element);
$result[$parts[0]] = explode(",", $parts[1]);
}
return $result;
}
$result = urlSplitter("prijs=0,209&orderby=price&order=undefined&posts_per_page=undefined");
var_dump($result);