I know this must be very basic but I really don't know how to solve this. I want to turn a php array to the following notation to be used inside a javascript script. These are countries which are passed to the js script in the initialization.
Source notation (PHP)
array(3) { [0]=> array(1) { ["code"]=> string(2) "AR" } [1]=> array(1) { ["code"]=> string(2) "CO" } [2]=> array(1) { ["code"]=> string(2) "BR" } }
Desired outcome (JS)
[ "AR", "FK","CO", "BO", "BR", "CL", "CR", "EC", "GT", "HN", "LT", "MX", "PA", "PY", "PE", "ZA", "UY", "VE"]
I can reformat the origin PHP array as desired, what I need to know is how to format it to get the desired outcome.
I am using the following code to pass the array to js:
echo "<script>var codes = " . json_encode($codes) . ";</script>";
Looks like the following would work for you:
<?php
$arr[0]['code'] = 'AR';
$arr[1]['code'] = 'CO';
$arr[2]['code'] = 'BR';
print_r($arr);
function extract_codes($var) { return $var['code']; }
print_r(array_map('extract_codes', $arr));
echo json_encode(array_map('extract_codes', $arr));
?>
Output:
Array
(
[0] => Array
(
[code] => AR
)
[1] => Array
(
[code] => CO
)
[2] => Array
(
[code] => BR
)
)
Array
(
[0] => AR
[1] => CO
[2] => BR
)
["AR","CO","BR"]
It works by mapping each of the two-letter codes down to a normal one-dimensional array, then passing it to json_encode.
Going with array_reduce:
$output = array_reduce($array, function($result, $item){
$result[] = $item['code'];
return $result;
}, array());
echo json_encode($output);
You need to loop through your PHP associative array and set the appropriate variables.
Like this:
$item = ''; // Prevent empty variable warning
foreach ($php_array as $key => $value){
if (isset($key) && isset($value)) { // Check to see if the values are set
if ($key == "code"){ $item .= "'".$value."',"; } // Set the correct variable & structure the items
}
}
$output = substr($item,'',-1); // Remove the last character (comma)
$js_array = "[".$output."]"; // Embed the output in the js array
$code = $js_array; //The final product
Related
Can someone help me about my problem... I have a php multidimensional array and i need to sort it by "PRICE" with PHP... I tried to use sort() but it don't work because every main array have a different currency name..
Here is an example of my array :
array(3) {
["MLN"]=>
array(1) {
["EUR"]=>
array(23) {
["FROMSYMBOL"]=>
string(3) "MLN"
["TOSYMBOL"]=>
string(3) "EUR"
["PRICE"]=>
float(0.01699)
}
}
["BTC"]=>
array(1) {
["EUR"]=>
array(23) {
["FROMSYMBOL"]=>
string(3) "BTC"
["TOSYMBOL"]=>
string(3) "EUR"
["PRICE"]=>
int(8769)
}
}
["LTC"]=>
array(1) {
["EUR"]=>
array(23) {
["FROMSYMBOL"]=>
string(3) "LTC"
["TOSYMBOL"]=>
string(3) "EUR"
["PRICE"]=>
float(141.47)
}
}
}
Is someone who have an idea to sort my currencies by PRICE?
Thanks a lot
You could use uasort():
uasort($array, function($a, $b) {
return $a['EUR']['PRICE'] - $b['EUR']['PRICE'];
});
I'm using an anonymous function in this example but you could also define the comparison function separately.
You could try something like this :
$sorted = [] ;
foreach ($array as $key => $item) {
$price = reset($item)['PRICE'] ;
$sorted[$price] = [$key => $item] ;
}
krsort($sorted);
$array = [];
foreach ($sorted as $sort) {
$keys = array_keys($sort) ;
$array[reset($keys)] = reset($sort) ;
}
unset($sorted);
print_r($array);
Will keep keys and sort array.
Output :
Array
(
[BTC] => Array
(
[EUR] => Array
(
[FROMSYMBOL] => BTC
[TOSYMBOL] => EUR
[PRICE] => 8769
)
)
[LTC] => Array
(
[EUR] => Array
(
[FROMSYMBOL] => LTC
[TOSYMBOL] => EUR
[PRICE] => 141.47
)
)
[MLN] => Array
(
[EUR] => Array
(
[FROMSYMBOL] => MLN
[TOSYMBOL] => EUR
[PRICE] => 0.01699
)
)
)
If you want a somewhat messy object oriented approach, I've made a class that is supposed to order an array of classes based on a shared property:
https://gist.github.com/kyrrr/b208693a59f184fe607660e0dfa8631d
A class that represents your data (quick and dirty):
class Exchange{
public $currencyName;
public $toSymbol;
public $rate;
function __construct($name, $to, $rate)
{
$this->currencyName = $name;
$this->toSymbol = $to;
$this->rate = $rate;
}
}
Then you can do:
$orderer = new PropertyOrderHelper();
$foo = new Exchange("MLN", "EUR", 0.0169);
$bar = new Exchange("BTC", "EUR", 20);
$exchanges = [$foo, $bar];
var_dump($orderer->orderBy($exchanges, "rate"));
var_dump($orderer->orderBy($exchanges, "rate", 'desc'));
I have been stumped on this for hours. I need to get the initial key of the array and the id. However I am only getting 1 result returned back.
Below is example code and also here is a link - https://3v4l.org/HdMtA
In short the expected output should be.
key 11111111 id val_somevalue5555
key 2222222 id val_somevalue25
I am only getting one result.
key 11111111 id val_somevalue5555
.
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $value)
{
$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);
Any help would be appreciated not sure if its the format of the json or what.
You are iterating the wrong thing.
Using print_r() to view the contents of the decoded array shows us that the thing you want to iterate over is - in fact - wrapped in another array.
print_r($jsonarr) returns this:
Array
(
[0] => Array
(
[11111111] => Array
(
[id] => val_somevalue5555
[customer] => Array
(
[32312] => Array
(
[name] => jane doe
)
)
)
[2222222] => Array
(
[id] => val_somevalue25
[customer] => Array
(
[32312234] => Array
(
[name] => jane doe
)
)
)
)
)
So, what you have is a JSON object wrapped in JSON array with said object being the only item inside it.
You want to either:
a) Get rid of those [ and ] things at the beginning and the end of your JSON, or... (if you don't have control over that JSON)
b) Iterate the inner object (PHP represents it as associative array):
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value) {
$newarr[] = ['key' => $key, 'id' => $value['id']];
}`
var_dump($newarr);
Behold: https://3v4l.org/qCvRd
Change your loop to use the key from the foreach loop itself: Like this
foreach($jsonarr as $key => $value)
{
$newarr[] = ['key' => $key, 'id' => $value[$key]['id']]; //this seems off but what do I know.
}
PHP uses a copy ( or reference?) of the array for Foreach, it can produce some unexpected things to happen. It does some spooky voodoo stuff some times, if you ever try editing the array structure while using reference in foreach such as foreach($var as $k => &$v ) look out. I swear one time it was like phantom items in the array ... lol
You need to change in you json structure and then make necessary changes which I mentioned below
$json = '{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr as $key=> $value)
{
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Are you looking this o/p:
$json = '[{
"11111111": {
"id": "val_somevalue5555",
"customer": {
"32312": {
"name": "john doe"
}
}
},
"2222222": {
"id": "val_somevalue25",
"customer": {
"32312234": {
"name": "jane doe"
}
}
}
}]';
$jsonarr = json_decode($json, true);
$newarr = [];
foreach($jsonarr[0] as $key => $value)
{
//echo "<br />".$key = key($value);
$newarr[] = ['key' => $key, 'id' => $value['id']];
}
var_dump($newarr);
Output:
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Or you can change the json structure as ankit patel said and follow his code...
Add another foreach to loop the elements of [0] if you will have more than this.
foreach($jsonarr as $value)
{
foreach($value as $key => $val){
$newarr[] = ['key' => $key, 'id' => $val['id']];
}
}
Result
array(2) {
[0]=>
array(2) {
["key"]=>
int(11111111)
["id"]=>
string(17) "val_somevalue5555"
}
[1]=>
array(2) {
["key"]=>
int(2222222)
["id"]=>
string(15) "val_somevalue25"
}
}
Test here
Hi I am working on very complex array operations.
I have $temp variable which stores pipe separated string like Height=10|Width=20
I have used explode function to convert into array and get specific output.
Below code i have try :
$product_attributes = explode("|",$temp)
//below output i get after the explode.
$product_attributes
Array(
[0]=>Height=10
[1]=>width=20
)
But i want to parse this array to separate one.
My expected output :
Array (
[0]=>Array(
[0] => Height
[1] => 10
)
[1]=>Array(
[0]=>Width
[1]=>20
)
)
Which function i need to used to get the desire output ?
Before downvoting let me know if i have made any mistake
You could try the below code. I've tested this and it outputs the result you've shown in your post.
$temp = 'Height=10|Width=20';
$product_attributes = explode('|', $temp);
$product_attributes2 = array();
foreach ($product_attributes as $attribute) {
$product_attributes2[] = explode('=', $attribute);
}
print_r($product_attributes2);
Try Below code
<?php
$temp = "Height=10|Width=20";
$product_attributes = explode("|", $temp);
foreach ($product_attributes as $k => $v) {
$product_attributes[$k] = explode('=', $v);
}
echo '<pre>';
print_r($product_attributes);
?>
check running answer here
Process your result by this:
$f = function($value) { return explode('=', $value); }
$result = array_map($f, $product_attributes);
One more option is to split the values in to one array and then build them from there.
$str = "Height=10|Width=20";
$arr = preg_split("/\||=/", $str);
$arr2= array();
$j=0;
for($i=0;$i<count($arr);$i++){
$arr2[$j][]= $arr[$i];
$arr2[$j][]= $arr[$i+1];
$i++;
$j++;
}
var_dump($arr2);
The output will be:
$arr = array(4){
0 => Height
1 => 10
2 => Width
3 => 20
}
$arr2 = array(2) {
[0]=>
array(2) {
[0]=>
string(6) "Height"
[1]=>
string(2) "10"
}
[1]=>
array(2) {
[0]=>
string(5) "Width"
[1]=>
string(2) "20"
}
}
To begin with I have an array (courses) like this:
array(2)
{
[0] => array(2)
{
["title"] => string "course1"
["code"] => string "001, 002, 003"
}
[1] => array(2)
{
["title"] => string "course2"
["ps_course_code"] => string "004"
}
}
Sometimes the 'code' will contain multiple codes as a comma separated string, other times 'code' will contain a single code.
To get individual codes I loop through the courses array and use explode to separate out the codes:
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
var_dump($courseInfo);
}
This gives me a new array for each course:
array(2)
{
["code"] => array(3)
{
[0] => string "001",
[1] => string "002",
[2] => string "003",
}
["title"] => string "course1"
}
array(2)
{
["code"] => array(1)
{
[0] => string "004"
}
["title"] => string "course2"
}
What I need though is a new array that contains every code and its title. So for some courses this means there will be multiple codes with the same title. E.g:
array(4)
{
[0] => array (2)
{
["code"] => string "001",
["title"] => string "course1"
}
[1] => array (2)
{
["code"] => string "002",
["title"] => string "course1"
}
[2] => array (2)
{
["code"] => string "003",
["title"] => string "course1"
}
[3] => array (2)
{
["code"] => string "004",
["title"] => string "course1"
}
}
I'm really struggling with this. Do I need another loop inside the first in order to create the final array?
foreach($courses as $course) {
$courseInfo['code'] = explode(",",$course["code"]);
$courseInfo['title'] = $course["title"];
// Another loop to create final array?
foreach($courseInfo as $value) {
$final['code'] = $value['code']; // I know this doesn't work!
$final['title'] = $value['title'];
}
}
var_dump($final);
I know this is long and I probably haven't explained this very well, so apologies!
You can get the desired output by looping over your first array:
$final = array();
foreach ($courses as $course) {
$codes = array_map('trim', explode(',', $course['code']));
foreach ($codes as $c) {
$final[] = array('code' => $c, 'title' => $course['title']);
}
}
Demo
You'd need to loop around the array of courses, not the full array.
i.e. something like this:
$i = 0;
foreach($courses as $course) {
$codes = explode(",",$course["code"]);
foreach($codes as $code) {
$final[$i]['code'] = $code;
$final[$i]['title'] = $course['title'];
$i++;
}
}
var_dump($final);
Easiest way to create array from the array value code is to loop through the array and explode the values, like you did.
$new_array = array(); //optionally for adding to new array
foreach($courses as $course)
{
$code = explode(',', $course['code']);
$trimmed_code = array_walk($code, function($value)
{
//trim the value to remove spaces before and after value
return trim($value);
});
$course['code'] = $trimmed_code;
//code for optionally add to new array
$new_array[] = array(
'code' => $code,
'title' => $course['title'],
);
}
foreach($courses as $course) {
$codes = explode(",",$course["code"]);
for($i=0;$i<count($codes); $i++){
$courseInfo['code'] = $codes[i];
$courseInfo['title'] = $course["title"];
}
var_dump($courseInfo);
}
Just working on something and can't find a simple solution to this problem without just looping through the array with a foreach. Does anyone have a simple solution for this
I want to turn this
&array(4) {
["a"]=>int(0)
["b"]=>int(1)
["c"]=>int(2)
["d"]=>int(3)
}
Into this
array(1) {
["a"]=>
array(1) {
[0]=>
array(1) {
["b"]=>
array(1) {
[0]=>
array(1) {
["c"]=>
array(1) {
[0]=>
array(1) {
["d"]=> int(1) //this value does not matter
}
}
}
}
}
}
}
The values don't matter at all I just need the keys to run against a array_intersect_key_recursive function that I have.
EDIT : The array has changed after testing it needs to be nested as an array of an array
I don't know how this could possibly end up helping you, but it was a fun exercise nonetheless.
$newArray = array();
$last = &$newArray;
$array = array_reverse(array_keys($array));
while ($item = array_pop($array)) {
if (!is_array($last)) {
$last = array();
}
$last[$item] = array(array());
$last = &$last[$item][0];
}
NOTE: I made this answer with the int(1). You said the value is not important so I'm not going to bother changing it for now, but you would have to do a bit more work if the value was important (probably something like get the value from the original array with $item as the key).
Another approach using recursion:
function toNestedArray(array $array, $index = 0) {
$return = array();
if ($index < count($array)) {
$return[$array[$index]] = toNestedArray($array, ++$index);
}
return $return;
}
Usage Example:
$flatArray = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$nestedArray = toNestedArray(array_keys($flatArray));
print_r($nestedArray);
Output:
Array
(
[a] => Array
(
[b] => Array
(
[c] => Array
(
[d] => Array
(
)
)
)
)
)