Simple question how can i transform this string:
"'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,"
To an array like this :
array['One'] = 1;
array['Two'] = 2;
array['Three'] = 3;
array['Four'] = 4;
Use regex and array_combine
preg_match_all('/\'(\w+)\'\s*=>\s*(\d+)/', $str, $m);
print_r(array_combine($m[1], $m[2]));
demo
$string = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$array = explode(',',$string);
foreach($array as $item){
$new_items = explode(' => ', $item);
$key = $new_items[0];
$value = $new_items[1];
$new_array[][$key] = $value;
}
var_dump($new_array);
Here a tested solution:
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$gen = new ArrayGenerator($input);
$this->assertSame([
'One' => 1,
'Two' => 2,
'Three' => 3,
'Four' => 4,
], $gen->translate());
and here complete code
use PHPUnit\Framework\TestCase;
class FooTest extends TestCase
{
public function testItems()
{
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$parser = new Parser($input);
$this->assertEquals([
"'One' => 1",
"'Two' => 2",
"'Three' => 3",
"'Four' => 4"
], $parser->items());
}
public function testKeyValue()
{
$input = "'One' => 1";
$parser = new KeyValue($input);
$this->assertEquals([
"'One'",
"1",
], $parser->items());
}
public function testKeyValueWithoutQuotas()
{
$input = "'One' => 1";
$parser = new KeyValue($input);
$this->assertEquals([
"One",
"1",
], $parser->itemsWithoutQuotas());
}
public function test()
{
$input = "'One' => 1,'Two' => 2,'Three' => 3,'Four' => 4,";
$gen = new ArrayGenerator($input);
$this->assertSame([
'One' => 1,
'Two' => 2,
'Three' => 3,
'Four' => 4,
], $gen->translate());
}
}
class ArrayGenerator
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function translate()
{
$parser = new Parser($this->input);
$parsed = $parser->items();
$trans = [];
foreach ($parsed as $item) {
$pair = new KeyValue($item);
$trans[$pair->itemsWithoutQuotas()[0]] = (int) $pair->itemsWithoutQuotas()[1];
}
return $trans;
}
}
class KeyValue
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function items()
{
$exploded = explode(' => ', $this->input);
return $exploded;
}
public function itemsWithoutQuotas()
{
$items = $this->items();
foreach ($items as $key => $item) {
$items[$key] = str_replace("'", "", $item);
}
return $items;
}
}
class Parser
{
private $input;
public function __construct(string $input)
{
$this->input = $input;
}
public function items()
{
$exploded = explode(',', $this->input);
$exploded = array_filter($exploded, function ($item) {
return $item != "";
});
return $exploded;
}
}
You can simply use the php function array_flip:
array_flip — Exchanges all keys with their associated values in an
array
Warning on collision:
If a value has several occurrences, the latest key will be used as its
value, and all others will be lost.
Example #2 array_flip() example : collision
<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);
print_r($flipped);
?>
The above example will output:
Array
(
[1] => b
[2] => c
)
Related
I have a multidimensional array like this:
array (
level1 => array ( level1.1,
level1.2)
level2 => array ( level2.1,
level2.2 => array( level2.2.1 => 'foo',
level2.2.2 => 'bar',
level2.2.3 => 'test')
)
)
As a result I want an array of strings like this
array ("level1/level1.1",
"level1/level1.2",
"level2/level2.1",
"level2/level2.2/level2.2.1",
"level2/level2.2/level2.2.2",
"level2/level2.2/level2.2.3")
Here is the code I tried
function displayArrayRecursively($array, string $path) : array {
if($path == "")
$result_array = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->displayArrayRecursively($value, $path . $key . '/');
} else {
$result_array[] = $path . $key; }
}
return $result_array;
}
Any idea how I can achieve this. I could use a reference array to populate, but I want to solve it with return values.
$array = [
'level1' => [
'level1.1',
'level1.2'
],
'level2' => [
'level2.1',
'level2.2' => [
'level2.2.1' => 'foo',
'level2.2.2' => 'bar',
'level2.2.3' => 'test'
]
]
];
function arrayParser(array $array, ?string $path=null) {
$res = [];
foreach($array as $key => $value) {
if(is_array($value)) {
$res[] = arrayParser($value, ($path ? $path.'/' : $path).$key);
}
else {
$res[] = $path.'/'.(!is_numeric($key) ? $key : $value);
}
}
return flatten($res);
}
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
$res = arrayParser($array); // result
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());
These Items should be put together into a JSON variable, including shop details:
{
"Name": "Shop 1",
"Time": "2015-12-01 12:50",
"Items": [
{
"Name": "Item-1",
"Count": "4",
"Charge": "100"
},
{
"Name": "Item-3",
"Count": "4",
"Charge": "100"
}
],
"Total": "800"
}
To get the outer JSON part I use:
class PrintData {
public $Name = "";
public $Time = "";
// ??
public $Total = "";
}
$printdata = new PrintData();
$printdata->Name=$shop_name;
$printdata->Time=$os_tsready;
// ?? $printdata->Item=$printitems;
$printdata->Total=1007;
However, I cannot figure out how I can get the two Item lines into JSON.
foreach($orderrecords as $or) {
$o_name=escape($or->o_name);
$o_cout=escape($or->o_count);
$o_charge=escape($or->o_charge);
How can I add the Item records correctly?
Fully OOP approach:
class Item {
public $Name;
public $Count;
public $Charge;
public function __construct($name, $count, $charge) {
$this->Name = $name;
$this->Count = $count;
$this->Charge = $charge;
}
}
class PrintData {
public $Items;
public $Name;
public $Time;
public $Total;
public function __construct($name, $time, $items, $total) {
$this->Name = $name;
$this->Time = $time;
$this->Total = $total;
$this->Items = $items;
}
}
$res = new PrintData(
"Shop 1",
"2015-12-01 12:50",
array(
new Item("Item-1", "4", "100"),
new Item("Item-3", "4", "100"),
),
"800"
);
echo json_encode($res);
Try this:
class PrintData {
public $Name = "";
public $Time = "";
public $Items = [];
public $Total = "";
}
$printdata = new PrintData();
$printdata->Name=$shop_name;
$printdata->Time=$os_tsready;
$printdata->Items=$printitems;
$printdata->Total=1007;
Where $printitems is an array of $item elements (like below)
And individually,
$item = array(
"Name" => "Item-1",
"Count" => "4",
"Charge" => "100"
);
$printdata->Items[0] = $item;
Online code: https://3v4l.org/R4s2C
$printitems should be an array here.
$printitems = array(
array('Name' => 'Item-1', 'Count' => '4', 'Charge' => '100'),
array('Name' => 'Item-3', 'Count' => '4', 'Charge' => '100')
);
Final Code
<?php
class PrintData {
public $Name = "";
public $Time = "";
// ??
public $Total = "";
}
$printdata = new PrintData();
$printdata->Name= 'Shop 1';
$printdata->Time='2015-12-01 12:50';
// ?? $printdata->Item=$printitems;
$printdata->Total='800';
$printitems = array(
array('Name' => 'Item-1', 'Count' => '4', 'Charge' => '100'),
array('Name' => 'Item-3', 'Count' => '4', 'Charge' => '100')
);
$printdata->Item = $printitems;
echo '<pre>';
// TILL NOW $printdata is an Object
// json_encode() converts $printdata into JSON Object
print_r(json_encode($printdata)); // THIS WILL GIVE YOUR DESIRED RESULT
I have no idea on how to do this, it'd probably use an explode but that'd not do exactly as I wanted.
Say I have a string:
a,1,1,0,0;0,1,1,0,0;r,1,1,0,0;
and I have an array:
a = atv
p = 330c
U = blista
c = BMW
D = bobcat
r = charger
I'd like it so that when it's called as a function on that string like seperateString($string); that it'd return something like "atv, charger"
I've tried some searching but to no avail have I found something which would return a string specific to the array.
Try this:
$string = "a,1,1,0,0;0,1,1,0,0;r,1,1,0,0;";
$array = array('a' => 'atv',
'p' => '330c',
'U' => 'blista',
'c' => 'BMW',
'D' => 'bobcat',
'r' => 'charger');
function separateString($array, $string) {
$result = array();
$chunks = preg_split('/[,;]/', $string);
foreach ($chunks as $chunk) {
if (array_key_exists($chunk, $array)) {
$result[] = $array[$chunk];
}
}
return $result;
}
print_r(separateString($array, $string));
Outputs:
Array
(
[0] => atv
[1] => charger
)
codepad example
The information you posted wasn't that great to go off of, but here's a start:
$string = "a,1,1,0,0;0,1,1,0,0;r,1,1,0,0;";
class Utility
{
protected static $classes = array(
'a' => 'atv',
'p' => '330c',
'U' => 'blista',
'c' => 'BMW',
'D' => 'bobcat',
'r' => 'charger'
);
public static function separateString($string)
{
$groups = explode(';', $string);
foreach ($groups as $group) {
$classId = array_shift(explode(',', $group));
if (array_key_exists($classId, self::$classes)) {
$classes[] = self::$classes[$classId];
}
}
return (isset($classes)) ? $classes : array();
}
}
$classes = Utility::separateString($string);
var_dump($classes);
/*
array(2) {
[0]=>
string(3) "atv"
[1]=>
string(7) "charger"
}
*/
Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}