Convert an Array of Strings, Each String Has Dot Separated Values, to a Multidimensional Array

Convert an array of strings, each string has dot separated values, to a multidimensional array

Try this.

<?php
$test = Array
(
0 => 'INBOX.Trash',
1 => 'INBOX.Sent',
2 => 'INBOX.Drafts',
3 => 'INBOX.Test.sub folder',
4 => 'INBOX.Test.sub folder.test 2',
);

$output = array();
foreach($test as $element){
assignArrayByPath($output, $element);
}
//print_r($output);
debug($output);
function assignArrayByPath(&$arr, $path) {
$keys = explode('.', $path);

while ($key = array_shift($keys)) {
$arr = &$arr[$key];
}
}

function debug($arr){
echo "<pre>";
print_r($arr);
echo "</pre>";
}

Parse dot-delimited strings and make a multidimensional array

Typically, I'd point you toward Convert dot syntax like "this.that.other" to multi-dimensional array in PHP and hammer this question as an under-researched duplicate, but you seem to have sufficient deviation in your desired output.

Your sample input and desired output are not well expressed in your question, but if I am reverse engineering your requirements correctly, you just need to explode the name values, do some conditional preparation, then push the values into the 3-level output array.

Code: (Demo)

$result = [];
foreach ($array as ['name' => $name, 'value' => $value]) {
$parts = explode('.', $name);
$parentKey = $parts[0] . 's';
$childKey = implode(array_splice($parts, 0, ctype_digit($parts[1]) ? 2 : 1));
$grandchildKey = implode('.', $parts); // $parts was reduced by array_splice()
if ($grandchildKey !== 'name') {
$result[$parentKey][$childKey][$grandchildKey] = $value;
}
}
var_export($result);

Output:

array (
'blocks' =>
array (
'block0' =>
array (
'backingIndex' => 2,
'rd.reqs' => 248907,
'rd.bytes' => 9842014208,
'rd.times' => 372870570891,
),
'block1' =>
array (
'backingIndex' => 30,
'rd.reqs' => 2871,
'rd.bytes' => 9677156,
'rd.times' => 620637479,
),
'block2' =>
array (
'backingIndex' => 30,
'rd.reqs' => 2871,
'rd.bytes' => 9677156,
'rd.times' => 620637479,
),
),
'vcpus' =>
array (
'vcpu0' =>
array (
'state' => 1,
'time' => 963654400000000,
'wait' => 0,
),
'vcpu1' =>
array (
'state' => 1,
'time' => 936409070000000,
'wait' => 0,
),
'vcpu2' =>
array (
'state' => 1,
'time' => 943396180000000,
'wait' => 0,
),
'vcpu3' =>
array (
'state' => 1,
'time' => 959496330000000,
'wait' => 0,
),
),
'balloons' =>
array (
'balloon' =>
array (
'current' => 16777216,
'maximum' => 34534530,
'swap_in' => 0,
'swap_out' => 0,
'major_fault' => 262,
'minor_fault' => 132293,
'unused' => 16153712,
'available' => 16396312,
),
),
)

Create comma separated strings from multidimensional array

A simple function that uses map to get the values into an array, and then join them up.

const arr=[{href:"http://www.somepath.com/car4.png",title:"Wheel"},{href:"http://www.somepath.com/car.png",title:"Top"},{href:"http://www.somepath.com/car1.png",title:"Side"},{href:"http://www.somepath.com/car5.png",title:"Saddle"},{href:"http://www.somepath.com/car6.png",title:"Front"}];

function createString(arr, key) {
return arr
.map(obj => `'${obj[key]}'`)
.join(', ');
}

console.log(JSON.stringify(createString(arr, 'href')));
console.log(JSON.stringify(createString(arr, 'title')));

make comma separated strings from multidimensional array

Given your comments I assume you are simply looking for Array.prototype.join(';'):

let array = [  ['a', 1],  ['b', 2],  ['c', 3]];
let comma_value = array.join(';');
console.log(comma_value); // 'a,1;b,2;c,3'

PHP string to multi level array

No recursion necessary:

$arrKeys = array_reverse(['lev1', 'lev2', 'lev3']);
$val = 'foo';

$result = $val;

foreach ($arrKeys as $key) {
$result = [$key => $result];
}

print_r($result);

// Array
// (
// [lev1] => Array
// (
// [lev2] => Array
// (
// [lev3] => foo
// )
//
// )
//
// )

Just build the array from the inside out.

How to join into a comma-separated string from array of arrays (multidimensional-array)?

This should work for you:

(Here I just get the column which you want with array_column() and simply implode it with implode())

echo implode(",", array_column($myAssociativeA, "type"));

Convert a list of dot noted strings into an associative array (PHP)

foreach only solution.

function convert(array $input)
{
$r = [];
foreach ($input as $dotted) {
$keys = explode('.', $dotted);
$c = &$r[array_shift($keys)];
foreach ($keys as $key) {
if (isset($c[$key]) && $c[$key] === true) {
$c[$key] = [];
}
$c = &$c[$key];
}
if ($c === null) {
$c = true;
}
}
return $r;
}

How dynamically create array in php with string index

$str = "eat.fruit.apple.good";
// Set pointer at top of the array
$arr = array();
$path = &$arr;
// Path is joined by dots
foreach (explode('.', $str) as $p)
// Make a next step
$path = &$path[$p];
$path = true;
print_r($arr); // $arr["eat"]["fruit"]["apple"]["good"] = true;

UPDATE Variant without pointer:

$str = "eat.fruit.apple.good";

$res = 'true';
foreach(array_reverse(explode('.', $str)) as $i)
$res = '{"' . $i . '":' . $res . '}';
$arr = json_decode($res, true);

JS: Convert dot string array to object tree

You could split the strings and use the parts as path to the nested array.

var array = ['catalog.product.name', 'catalog.product.description', 'catalog.product.status', 'catalog.product_attribute_set.name', 'catalog.product_attribute_set.type'],    result = [];
array.forEach(s => s .split('.') .reduce((object, value) => { var item = (object.children = object.children || []).find(q => q.value === value); if (!item) object.children.push(item = { value, label: value }) return item; }, { children: result }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Convert string into multidimensional array in Neo4J

Using APOC Procedures, you can use the apoc.convert.fromJsonList() function to convert the list, though you'll need to make sure each of the subitems in the arrays is quoted so they'll be interpreted as strings.

WITH "[['date1', 'User1', 'Rating1'], ['date2', 'User2', 'Rating2'], ['date3', 'User3', 'Rating3']]" as inputString
WITH apoc.convert.fromJsonList(input) as input
RETURN input[2][0] //returns 'date3'

Just a note, the conversion functions are currently missing in the APOC docs, but you can reference them and their signature by entering this in the Neo4j browser:

CALL apoc.help('fromjson')

And now for the bad news.

Although you can do this with literal input and parameters and convert from properties which are JSON strings, you cannot use a nested list as a property of a node or relationship, that's just a current limitation of the properties implementation.

That said, this feels like your modeling may need some improvement. We'd recommend using separate nodes for your reviews rather than this nested structure, so something like:

(:Product)-[:HAS_REVIEW]->(:Review)

Where the :Review node has the date and rating, and either has the user ID, or has a relationship to the user node who rated the product.

Usage would look something like:

MATCH (p:Product {id:12345})-[:HAS_REVIEW]->(r)
WITH p, collect(r) as reviews
...

At that point you have an (unordered) array of the review nodes, and can do index access to get a review at a particular index, then use dot notation to access the property or properties you want. If you want ordering, you'll need to do an explicit ORDER BY before the collect(), and you'll need something to order it by, probably the date of the review.



Related Topics



Leave a reply



Submit