Convert and rewrite an array - php

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.

Related

How to get the value of an element from a multidimensional JSON string array in PHP

This is the array:
Array
(
[0] => Array
(
[product_details] => {"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}
)
[1] => Array
(
[product_details] => {"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}
)
[2] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
[3] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
)
What I need is to create a new simple array containing the values from all the "id" elements.
Hope this simple foreach will be helpful for you.
Solution 1: Try this code snippet here
$result=array();
foreach($array as $value)
{
$array= json_decode($value["product_details"],true);
$result[]=$array[key($array)]["id"];
}
print_r($result);
Here we are using array_column to extract product_details then we are using to array_map to iterate over $personalDetails which contain all the JSON's then we are using to key function which will return first key of the array, and through that key we are accessing, its id.
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$array = Array
(
0 => Array
(
"product_details" => '{"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}'
),
1 => Array
(
"product_details" => '{"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}'
),
2 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
),
3 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
)
);
$personalDetails= array_column($array, "product_details");
$result=array_map(function($value){
$array=json_decode($value,true);
return $array[key($array)]["id"];
}, $personalDetails);
print_r($result);
Output:
Array
(
[0] => 110
[1] => 109
[2] => 108
[3] => 108
)
use array_column and json_decode
$new_one = array_column($array,'product_details');
$new_array=[];
foreach($new_one as $key=>$row)
{
foreach(json_decode($row,true) as $key1=>$row1)
{
$new_array[]=$row1['id'];
}
}
print_r($new_array);
you may use array_map & array_value to achieve this,
here is a quick example, and you need to modify it to be fit with your needs :
$ar = [
0 => ['product_details' => '{"5f93f983524def3dca464469d2cf9f3e":{"id": 3}}'],
1 => ['product_details' => '{"2723d092b63885e0d7c260cc007e8b9d":{"id": 8}}'],
2 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 5}}'],
3 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 1}}'],
];
$ar = array_map(function ($value) {
return array_values(json_decode($value['product_details'], true))[0]['id'];
}, $ar);
print_r($ar);
live demo : https://3v4l.org/koXee
Try this code, live demo
print_r(array_column(array_map(function($v){return current(json_decode($v));},array_column($array, 'product_details')), 'id'));
You "product_details" seems to be a JSON string. Loop through your array, decode the JSON and store the "id" in a new array.

Codeigniter PHP create two different array from one

I'm newbie of codeigniter and PHP.
Can I separate an array into two different arrays?
This is my $array:
Array (
[0] => Array
(
[Name] => mark
[Surname] => mark
)[1] => Array
(
[Name] => greg
[Surname] => greg
)
)
Is it possible to create an array of $mark and another with $greg?
If you want to use the value of Name as your variable name: Variable variables
foreach ($arrays as $array) {
if (isset($array['Name'])) {
$$array['Name'] = $array;
}
}
print_r($mark);
You may use eval() if you want to set a string value and make it a variable.
<?php
$arrays = array(
array(
'Name' => 'mark',
'Surname' => 'mark'
),
array(
'Name' => 'greg',
'Surname' => 'greg'
)
);
//I'd use foreach()
foreach ($arrays as $array) {
eval("$".$array['Name']." = array('Name'=>'{$array['Name']}','Surname'=>'{$array['Surname']}',);");
}
echo '<pre>';
var_dump($mark, $greg);
echo '</pre>';

Flatten 3rd level of array to create indexed array of associative rows

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
)
);

php: getting only top value in multidimensional array

My nested array looks like:
[Minion] => Array
(
[old_first_name] => "\345\205\265"
[old_last_name] => "\345\274\265"
[old_name] => "\345\205\265\345\274\265"
)
[Evil Minion] => Array
(
[old_first_name] => "\347\251\216"
[old_last_name] => "\345\274\265"
[old_name] => "\345\274\265\347\251\216"
)
[Minion 2] => Array
(
[old_first_name] => "\345\212\233"
[old_last_name] => "\345\274\265"
[old_name] => "\345\274\265\345\212\233"
)
How do I just get Minion, Evil Minion, and Minion 2?
I tried a for loop but it's just looping through the contents of Minion which isn't what I want!
Use the array_keys function:
$keys = array_keys($array);
var_dump($keys);
This works for any array, whether it's one-dimensional or multi-dimensional.
Do this way.. you need to nest furthermore
<?php
$arr= array(
'Minion' => Array
(
'old_first_name' => "\345\205\265",
'old_last_name' => "\345\274\265",
'old_name' => "\345\205\265\345\274\265"
),
'Evil Minion' => Array
(
'old_first_name' => "\347\251\216",
'old_last_name' => "\345\274\265",
'old_name' => "\345\274\265\347\251\216"
),
'Minion 2' => Array
(
'old_first_name' => "\345\212\233",
'old_last_name' => "\345\274\265",
'old_name' => "\345\274\265\345\212\233"
)
);
foreach($arr as $arr1)
{
foreach($arr1 as $k=>$v)
{
echo "$k => $v";
}
}
Demo
You'd be interested in array_keys to just fetch the keys...
$keys = array_keys($arr);
Since this returns an array of the keys, you may further loop through it using a for-each construct.

Count number of different strings?

I have an array that looks like
Array
(
[1] => Array
(
[0] => Date
[1] => Action
)
[2] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_TWEET
)
[3] => Array
(
[0] => 2011-01-22 11:23:19
[1] => SHARE_FACEBOOK
)
and many other different values (about 10), what I want to do is I want to count the number of times a string is in the array. I was going to use array_count_values but it doesn't count multidimensional arrays.
Any other options?
This could be done by first flattening the array, and then using array_count_values() on it:
For flattening, here is the trick:
$array = call_user_func_array('array_merge', $arrays);
And then:
$counts = array_count_values($array);
Output:
array (
'Date' => 1,
'Action' => 1,
'2011-01-22 11:23:19' => 2,
'SHARE_TWEET' => 1,
'SHARE_FACEBOOK' => 1,
)
Full code:
$array = call_user_func_array('array_merge', $arrays);
var_export(array_count_values($array));
Any time you're dealing with arrays, especially with loops in PHP I can't string enough suggest you look at the array documentation, You'd be suprised how quickly you realise most of the loops in your code is unnecessary. PHP has a built in function to achieve what you're after called array_walk_recursive. And since you're using PHP5 you can use closures rather that create_function (which can be very troublesome, especially to debug, and can't be optimised by the PHP interpreter afik)
$strings = array();
array_walk_recursive($arr, function($value, $key) use (&$strings) {
$strings[$value] = isset($strings[$value]) ? $strings[$value]+1 : 1;
});
I know, unary statements aren't always clear, but this one is simple enough, but feel free to expand out the if statement.
The result of the above is:
print_r($strings);
Array
(
[Date] => 1,
[Action] => 1,
[2011-01-22 11:23:19] => 2,
[SHARE_TWEET] => 1,
[SHARE_FACEBOOK] => 1,
)
Pseudo Code
$inputArray = // your array as in the example above
foreach ($inputArray as $key => $value) {
$result[$value[1]] = $result[$value[1]] + 1;
}
var_dump($result);
Here is a way to do the job:
$arr = Array (
1 => Array (
0 => 'Date',
1 => 'Action'
),
2 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_TWEET'
),
3 => Array (
0 => '2011-01-22 11:23:19',
1 => 'SHARE_FACEBOOK'
)
);
$result = array();
function count_array($arr) {
global $result;
foreach($arr as $k => $v) {
if (is_array($v)) {
count_array($v);
} else {
if (isset($result[$v])) {
$result[$v]++;
} else {
$result[$v] = 1;
}
}
}
}
count_array($arr);
print_r($result);
output:
Array
(
[Date] => 1
[Action] => 1
[2011-01-22 11:23:19] => 2
[SHARE_TWEET] => 1
[SHARE_FACEBOOK] => 1
)

Categories