I want to dissect an array like this:
[
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
]
To a format like this:
{
"ID" : 1,
"UUID" : 1,
"pushNotifications" :
{
"sent" : 1,
"tapped" : 1
},
"campaigns" :
{
"boundDate" : 1,
"endDate" : 1,
"pushMessages" :
{
"endDate" : 1
}
}
}
It would be great if I could just set a value on an associative array in a keypath-like manner:
//To achieve this:
$dissected['campaigns']['pushMessages']['sentDate'] = 1;
//By something like this:
$keypath = 'campaigns.pushMessages.sentDate';
$dissected{$keypath} = 1;
How to do this in PHP?
You can use :
$array = [
"ID",
"UUID",
"pushNotifications.sent",
"campaigns.boundDate",
"campaigns.endDate",
"campaigns.pushMessages.sentDate",
"pushNotifications.tapped"
];
// Build Data
$data = array();
foreach($array as $v) {
setValue($data, $v, 1);
}
// Get Value
echo getValue($data, "campaigns.pushMessages.sentDate"); // output 1
Function Used
function setValue(array &$data, $path, $value) {
$temp = &$data;
foreach(explode(".", $path) as $key) {
$temp = &$temp[$key];
}
$temp = $value;
}
function getValue($data, $path) {
$temp = $data;
foreach(explode(".", $path) as $ndx) {
$temp = isset($temp[$ndx]) ? $temp[$ndx] : null;
}
return $temp;
}
function keyset(&$arr, $keypath, $value = NULL)
{
$keys = explode('.', $keypath);
$current = &$arr;
while(count($keys))
{
$key = array_shift($keys);
if(!isset($current[$key]) && count($keys))
{
$current[$key] = array();
}
if(count($keys))
{
$current = &$current[$key];
}
}
$current[$key] = $value;
}
function keyget($arr, $keypath)
{
$keys = explode('.', $keypath);
$current = $arr;
foreach($keys as $key)
{
if(!isset($current[$key]))
{
return NULL;
}
$current = $current[$key];
}
return $current;
}
//Testing code:
$r = array();
header('content-type: text/plain; charset-utf8');
keyset($r, 'this.is.path', 39);
echo keyget($r, 'this.is.path');
var_dump($r);
It's a little rough, I can't guarantee it functions 100%.
Edit: At first you'd be tempted to try to use variable variables, but I've tried that in the past and it doesn't work, so you have to use functions to do it. This works with some limited tests. (And I just added a minor edit to remove an unnecessary array assignment.)
In the meanwhile, I came up with (another) solution:
private function setValueForKeyPath(&$array, $value, $keyPath)
{
$keys = explode(".", $keyPath, 2);
$firstKey = $keys[0];
$remainingKeys = (count($keys) == 2) ? $keys[1] : null;
$isLeaf = ($remainingKeys == null);
if ($isLeaf)
$array[$firstKey] = $value;
else
$this->setValueForKeyPath($array[$firstKey], $value, $remainingKeys);
}
Sorry for the "long" namings, I came from the Objective-C world. :)
So calling this on each keyPath, it actually gives me the output:
fields
Array
(
[0] => ID
[1] => UUID
[2] => pushNotifications.sent
[3] => campaigns.boundDate
[4] => campaigns.endDate
[5] => campaigns.pushMessages.endDate
[6] => pushNotifications.tapped
)
dissectedFields
Array
(
[ID] => 1
[UUID] => 1
[pushNotifications] => Array
(
[sent] => 1
[tapped] => 1
)
[campaigns] => Array
(
[boundDate] => 1
[endDate] => 1
[pushMessages] => Array
(
[endDate] => 1
)
)
)
Related
I have a array multi level
$array = array("14529" => array("900" => array("87" => array() ) ) );
print_r(array_keys($array)); // result array("14529");
How to merge this array to single array
$array = array("14529", "900", "87");
Here is a function that does what you want. It is done recursively, so it doesn't matter how deep the array is.
function mergeArrayMultiKeyToSingleArray($array, $result=[])
{
foreach($array as $key => $value) {
$result[] = $key;
if(is_array($value)) {
$result = mergeArrayMultiKeyToSingleArray($value, $result);
}
}
return $result;
}
// USAGE:
$array = array("14529" => array("900" => array("87" => array() ) ) );
$array = mergeArrayMultiKeyToSingleArray($array);
// $array is now ["14529", "900", "87"]
The solution using RecursiveIteratorIterator class:
$arr = ["14529" => ["900" => ["87" => [] ] ] ];
$keys = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) {
$keys[] = $k;
}
print_r($keys);
The output:
Array
(
[0] => 14529
[1] => 900
[2] => 87
)
I did this using class
class ArrayStripper
{
private $items = [];
public function strip($arrayOrItem)
{
if(is_array($arrayOrItem))
{
foreach ($arrayOrItem as $item)
{
$this->strip($item);
}
}
else
{
$this->items[] = $arrayOrItem;
}
}
public function get()
{
return $this->items;
}
}
$array = [1 , [2,3] , 4 , [[5 , 6 , 7] , [8 ,9] , 10]];
$stripper = new ArrayStripper();
$stripper->strip($array);
var_dump($stripper->get());
I have array of object as
$a = [{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}];
here i want to create new array of abject in which duplicate object will not be there (invoice_id) as new array will be having first object of same invoice_id. i was doing like this.
foreach ($a as $key => $value) {
if(isset($new)) {
foreach ($new as $k => $val) {
if($val->id != $value->id) {
$new[] = $value;
}
}
}else{
$new[] = $value;
}
}
my new array will be like
$new = [{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}]
but it is not giving desired output . What should be done ?
Since you tagged this as Laravel question use collections.
Less code (one line!) and performance hit is non-existent.
$a = json_decode('[{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}]');
$result = collect($a)->groupBy('invoice_id');
After OP edited question:
$result = collect($a)->unique('invoice_id')->values()->toArray();
results in:
=> [
{#826
+"id": "20",
+"invoice_id": "123",
},
{#824
+"id": "22",
+"invoice_id": "125",
},
]
or using ->toJson() instead of ->toArray()
"[{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}]"
Please try the below code with simple logic,
$temp = $new = array();
$b = json_decode($a, true);
foreach ($b as $key => $val) {
if(!in_array($val['invoice_id'], $temp)) {
$temp[$val['id']] = $val['invoice_id'];
$new[] = array('id' => $val['id'], 'invoice_id' => $val['invoice_id']);
}
}
print_r($new);
I am just creating a temp array to store only the unique invoice_id to compare in a loop.
It gives the below result,
Array
(
[0] => Array
(
[id] => 20
[invoice_id] => 123
)
[1] => Array
(
[id] => 22
[invoice_id] => 125
)
)
$result = [];
foreach ($a as $data) {
$result[$data->id] = $data;
}
var_dump(array_values($results));
Try this
$a = json_decode($a);
$invoiceid = [];
$unique = [];
foreach ($a as $key => $value) {
if(!in_array($value->invoice_id,$invoiceid)) {
$invoiceid[] = $value->invoice_id;
$unique[] = $value;
}
}
echo $a = json_encode($unique);
I have a problem approaching an issue i have, i need to group arrays by key value
I have 3 foreach functions
foreach ($report_phonecall as $key=>$value) {
$phonecalls[$value['datum']] = $value['broj'];
};
foreach ($report_meeting as $key=>$value) {
$meetings[$value['datum']] = $value['broj'];
}
foreach ($report_notes as $key=>$value) {
$notes[$value['datum']] = $value['broj'];
}
That give me array
$phonecall = Array ( [2016-07-13] => 2 [2016-07-14] => 1 [2016-07-19] =>1 )
$meetings = Array ( [2016-07-13] => 1 [2016-07-14] => 1 )
$notes = Array ( [2016-07-19] => 1 )
I need to merge them into 1 array foreach date like this
Array(2016-07-13 => array([phonecalls]=>2, [meetings]=>1, [notes]=>0)) 2016-07-14 => array([phonecalls]=>1, [meetings]=> 1, [notes]=>0).... etc
I want to group/sort them by key value.
Going by
$group_reports[$value[key]] = $value['broj'][$phonecalls][$meetings][$notes]
Im not sure how to define it
How about like this?
$phonecall = ['2016-07-13' => 2, '2016-07-14' => 1, '2016-07-19' => 1];
$meetings = ['2016-07-13' => 1, '2016-07-14' => 1];
$notes = ['2016-07-19' => 1];
// Get *all* possible dates
$keys = array_unique(array_keys($phonecall+$meetings+$notes));
foreach($keys as $key) {
$final[$key] = [
'phonecalls' => isset($phonecall[$key]) ? $phonecall[$key] : 0,
'meetings' => isset($meetings[$key]) ? $meetings[$key] : 0,
'notes' => isset($notes[$key]) ? $notes[$key] : 0
];
}
Please use below code for merge array
$finalArr = array();
foreach($phonecall as $key=>$val){
$finalArr[$key]['phonecalls'] = $val;
$finalArr[$key]['meetings'] = 0;
$finalArr[$key]['notes'] = 0;
}
foreach($meetings as $key=>$val){
if(array_key_exists($key, $finalArr)){
$finalArr[$key]['meetings'] = $val;
} else {
$finalArr[$key]['phonecalls'] = 0;
$finalArr[$key]['meetings'] = $val;
$finalArr[$key]['notes'] = 0;
}
}
foreach($notes as $key=>$val){
if(array_key_exists($key, $finalArr)){
$finalArr[$key]['notes'] = $val;
} else {
$finalArr[$key]['phonecalls'] = 0;
$finalArr[$key]['meetings'] = 0;
$finalArr[$key]['notes'] = $val;
}
}
I have the next INI file:
a.b.c = 1
a.b.d.e = 2
I am parsing this file using parse_ini_file. And it returns:
array(
'a.b.c' => 1,
'a.b.d.e' => 2
)
But I want to create a multidimensional array. My outout should be:
array(
'a' => array(
'b' => array(
'c' => 1,
'd' => array(
'e' => 2
)
)
)
)
Thank you in advance.
This is how I see it:
<?php
class ParseIniMulti {
public static function parse($filename) {
$ini_arr = parse_ini_file($filename);
if ($ini_arr === FALSE) {
return FALSE;
}
self::fix_ini_multi(&$ini_arr);
return $ini_arr;
}
private static function fix_ini_multi(&$ini_arr) {
foreach ($ini_arr AS $key => &$value) {
if (is_array($value)) {
self::fix_ini_multi($value);
}
if (strpos($key, '.') !== FALSE) {
$key_arr = explode('.', $key);
$last_key = array_pop($key_arr);
$cur_elem = &$ini_arr;
foreach ($key_arr AS $key_step) {
if (!isset($cur_elem[$key_step])) {
$cur_elem[$key_step] = array();
}
$cur_elem = &$cur_elem[$key_step];
}
$cur_elem[$last_key] = $value;
unset($ini_arr[$key]);
}
}
}
}
var_dump(ParseIniMulti::parse('test.ini'));
It's actually quite simple, you only need to change the format of the array you already have by exploding it's key:
$ini_preparsed = array(
'a.b.c' => 1,
'a.b.d.e' => 2
);
$ini = array();
foreach($ini_preparsed as $key => $value)
{
$p = &$ini;
foreach(explode('.', $key) as $k)
$p = &$p[$k];
$p = $value;
}
unset($p);
print_r($ini);
Output:
Array
(
[a] => Array
(
[b] => Array
(
[c] => 1
[d] => Array
(
[e] => 2
)
)
)
)
See as well: String with array structure to Array.
Have a look at the Zend_Config_Ini class. It does what you want, you can use it standalone (without the rest of Zend Framework) and as a bonus it supports section inheritance.
With the toArray method you can create an array from the config object.
Take a look at PHProp.
Similar to Zend_Config_Ini, but you can refer to a key in your config like ${key}
It's a my class for parsing config ini files to a multidimensional array:
class Cubique_Config {
const SEPARATOR = '.';
private static $_data = null;
public static function get() {
if (is_null(self::$_data)) {
$commonIniFile = APP . '/config' . '/common.ini';
$envIniFile = APP . '/config' . '/' . ENV . '.ini';
if (!file_exists($commonIniFile)) {
throw new Exception('\'' . $commonIniFile . '\' config file not found');
}
if (!file_exists($envIniFile)) {
throw new Exception('\'' . $envIniFile . '\' config file not found');
}
$commonIni = parse_ini_file($commonIniFile);
$envIni = parse_ini_file($envIniFile);
$mergedIni = array_merge($commonIni, $envIni);
self::$_data = array();
foreach ($mergedIni as $rowKey => $rowValue) {
$explodedRow = explode(self::SEPARATOR, $rowKey);
self::$_data = array_merge_recursive(self::$_data, self::_subArray($explodedRow, $rowValue));
}
}
return self::$_data;
}
private static function _subArray($explodedRow, $value) {
$result = null;
$explodedRow = array_values($explodedRow);
if (count($explodedRow)) {
$firstItem = $explodedRow[0];
unset($explodedRow[0]);
$result[$firstItem] = self::_subArray($explodedRow, $value);
} else {
$result = $value;
}
return $result;
}
}
Consider following array
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n')
);
Here I would like to sort with head and membkey. Top element of same membkey element should have 'head=y' and echoed as,
$details = array(
array('lname'=>'A', 'fname'=>'P','membkey'=>700,'head'=>'y'),
array('lname'=>'E', 'fname'=>'T','membkey'=>700,'head'=>'n'),
array('lname'=>'C', 'fname'=>'R','membkey'=>700,'head'=>'n'),
array('lname'=>'D', 'fname'=>'S','membkey'=>540,'head'=>'y'),
array('lname'=>'B', 'fname'=>'Q','membkey'=>540,'head'=>'n')
);
I tried it as follows
function orderbymemberKey( $a, $b ){
if ( $a[membkey] == $b[membkey] )
return 0;
return($a[membkey] < $b[membkey] )? -1 :1;
}
usort( $details, orderbymemberKey );
and it successfully order by membkey.
Any suggestions please.
You're half way there (though you were sorting backwards for membkey based on your example):
function order_by_member_key($a, $b)
{
if ($a['membkey'] == $b['membkey'])
{
// membkey is the same, sort by head
if ($a['head'] == $b['head']) return 0;
return $a['head'] == 'y' ? -1 : 1;
}
// sort the higher membkey first:
return $a['membkey'] < $b['membkey'] ? 1 : -1;
}
usort($details, "order_by_member_key");
Is this array being pulled from a database? Because, if so, you should be able to make use of ORDER BY clauses to clean it up outside of php.
<?php
$membkey = array();
$head = array();
foreach ($details as $key => $row) {
$membkey[$key] = $row['membkey'];
$head[$key] = $row['head'];
}
array_multisort($membkey, SORT_DESC, $head, SORT_DESC, $details);
print_r($details);
Or, an even more generic solution:
function sort_by($array) {
$arguments = func_get_args();
$array = array_pop($arguments);
$variables = array();
foreach ($arguments as $index => $key) {
$variables[] = '$arguments['.$index.']';
if ($index % 2 == 0) {
$arguments[$index] = array();
foreach ($array as $row) $arguments[$index][] = $row[$key];
}
}
// call_user_func_array will not work in this case
eval('array_multisort('.implode(', ', $variables).', $array);');
return $array;
}
print_r(sort_by('membkey', SORT_DESC, 'head', SORT_DESC, $details));
Ugly but someone wrote a function on php.net:
http://php.net/manual/en/function.sort.php
<?php
$array[0]['name'] = 'Chris';
$array[0]['phone'] = '3971095';
$array[0]['year'] = '1978';
$array[0]['address'] = 'Street 1';
$array[1]['name'] = 'Breanne';
$array[1]['phone'] = '3766350';
$array[1]['year'] = '1990';
$array[1]['address'] = 'Street 2';
$array[2]['name'] = 'Dusty';
$array[2]['phone'] = '1541120';
$array[2]['year'] = '1982';
$array[2]['address'] = 'Street 3';
function multisort($array, $sort_by, $key1, $key2=NULL, $key3=NULL, $key4=NULL, $key5=NULL, $key6=NULL){
// sort by ?
foreach ($array as $pos => $val)
$tmp_array[$pos] = $val[$sort_by];
asort($tmp_array);
// display however you want
foreach ($tmp_array as $pos => $val){
$return_array[$pos][$sort_by] = $array[$pos][$sort_by];
$return_array[$pos][$key1] = $array[$pos][$key1];
if (isset($key2)){
$return_array[$pos][$key2] = $array[$pos][$key2];
}
if (isset($key3)){
$return_array[$pos][$key3] = $array[$pos][$key3];
}
if (isset($key4)){
$return_array[$pos][$key4] = $array[$pos][$key4];
}
if (isset($key5)){
$return_array[$pos][$key5] = $array[$pos][$key5];
}
if (isset($key6)){
$return_array[$pos][$key6] = $array[$pos][$key6];
}
}
return $return_array;
}
//usage (only enter the keys you want sorted):
$sorted = multisort($array,'year','name','phone','address');
print_r($sorted);
//output:
Array ( [0] => Array ( [year] => 1978 [name] => Chris [phone] => 3971095 [address] => Street 1 ) [2] => Array ( [year] => 1982 [name] => Dusty [phone] => 1541120 [address] => Street 3 ) [1] => Array ( [year] => 1990 [name] => Breanne [phone] => 3766350 [address] => Street 2 ) )