Php multidimentional array convert to one dimentional [duplicate] - php

This question already has answers here:
Multidimensional array to array
(4 answers)
Closed 6 years ago.
I have an array which consist monthly information as shown below :
[appr] => Array
(
[0] => Array
(
[month] => August
[approd] => 23
)
[1] => Array
(
[month] => September
[approd] => 546
)
[2] => Array
(
[month] => October
[approd] => 234
)
)
I want the output as below
[appr] => Array(
August => 23,
September => 546,
October => 234
)
can anybody help me to achieve this using php.

If you're looking for a simple one-liner solution, use array_column() and array_combine() functions.
Try this:
$array['appr'] = array_combine(array_column($array['appr'], "month"), array_column($array['appr'], "approd"));

Simply loop in your array and create a new array
$array = array(array('month'=>'August','approd'=>'23'),array('month'=>'September','approd'=>'56'),array('month'=>'October','approd'=>'234'),);
$new = array();
foreach($array as $val) {
$new['appr'][$val['month']] = $val['approd'];
}

"One-line" solution using array_column function:
$arr['appr'] = array_column($arr['appr'], 'approd', 'month');
print_r($arr);
The output:
Array
(
[appr] => Array
(
[August] => 23
[September] => 546
[October] => 234
)
)

Another option is to use array_walk_recursive:
<?php
$array = array(
0 => array(
'something',
),
1 => array(
'else',
)
);
// If the keys are unique
$newArray = array();
array_walk_recursive($array, function($v, $k) use (&$newArray) {
$newArray[$k] = $v;
});
// If you have duplicate keys
$newArray = array();
array_walk_recursive($array, function($v) use (&$newArray) {
$newArray[] = $v;
});
And finally output the result:
print_r($newArray);
Resources
array_walk_recursive - Manual

Related

Create multidimensional array from multiple arrays in PHP [duplicate]

This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 5 months ago.
I have two arrays:
Array ( [0] => label [1] => data )
Array ( [0] => 1 [1] => 2 )
And I need merge them in a array like this:
Array ( [0] => Array ( [label] => 1 [data] => 2 ) )
I have tried:
for ($i=0; $i < count($inputs); $i++) {
$new = array($cols[$i] => $inputs[$i]);
$data[] = $new;
}
Any help is welcome ;)
You can simply use array_combine:
Creates an array by using one array for keys and another for its
values
$arr1 = array(0 => 'label', 1 => 'data');
$arr2 = array(0 => 1, 1 => 2);
$arr3 = array_combine($arr1, $arr2);
print_r($arr3);
Result:
Array
(
[label] => 1
[data] => 2
)
Try it
You can do it like so if you want to use a loop
$array1 = ['label', 'data'];
$array2 = [1, 2];
$array_merged = [];
foreach($array1 as $key => $value) {
$array_merged[$value] = $array2[$key];
}
var_dump($array_merged);
http://sandbox.onlinephpfunctions.com/code/c4e5bc71df53ebdafb0a54d43c3eadb4ea4cd241

How do I return a key value by providing another key value in a multidimensional array in PHP?

Assume I have an array like the one below:
Array
(
[0] => Array
(
[town_id] => 1
[town_name] => ABC
[town_province_id] => 7
)
[1] => Array
(
[town_id] => 2
[town_name] => DEF
[town_province_id] => 4
)
[2] => Array
(
[town_id] => 3
[town_name] => GHI
[town_province_id] => 2
)
)
I want to provide value "DEF" in the above array and return value "2".
Please help me.
You can use in_array to get your result.
$input = 'DEF';
foreach($array as $key=>$value){
if(in_array($input,$value)){
$town_id = $value['town_id'];
}
}
print_r($town_id);
You can use array_search with array_column
$key = array_search('DEF', array_column($array, 'town_name'));
Example:
$data = array( array('town_id' => 1, 'town_name' => 'ABC'), array('town_id' => 2, 'town_name' => 'DEF') );
print_r($data);
$key = array_search('DEF', array_column($data, 'town_name'));
print_r($data[$key]['town_id']); // it will have 2
Use array_search and array_column
$key = array_search('DEF', array_column($your_arr, 'town_name'));
$your_arr[$key]['town_id']; // should return DEF
Note: array_column works from PHP 5 >= 5.5.0

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.

Remove duplicate array on the base of key in multidimendional array PHP [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 6 years ago.
From following array key with ID 16 is comming twice. Hown can we remove this this duplicate ID. (REMOVE IF ID IS DUPLICATE OTHER FIELDS IGNORE)
Array
(
[1] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:12:53
)
[2] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:01:54
)
[3] => Array
(
[ID] => 3
[username] => himanshu
[message-time] => 2016-08-15 12:53:38
)
[4] => Array
(
[ID] => 15
[username] => dawinder
[message-time] => 2016-08-10 11:40:33
)
)
I Got solution
I have develop this function for same :
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
Now, call this function anywhere from your code,
something like this,
$details = unique_multidim_array($array_name,'key');
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Read this:http://php.net/manual/en/function.array-unique.php
For Example
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output will be:
Array
(
[a] => green
[0] => red
[1] => blue
)

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