how to format array from string in php? - php

I want if the first number in the string is 2 the output will be 2 array. How to explode as each array from string.
My code
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$data = explode(',',$str);
$out = array();
for($i=1;$i < count($data)-1;$i++){
$out[]= explode(';',$data[$i]);
}
$i = $out[0][0];
foreach ($out as $key => $value) {
for($a=0;$a < $i; $a++){
echo $value[$a]. "<br/>";
}
}
?>
I get the result 221107-09-201607-09-201608-09-201610-09-201613
But I want this format
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
//format will be split by semicomma ;
$arr1 = Array('2','1','07-09-2016','08-09-2016','1','100.00');
$arr2 = Array('2','1','07-09-2016','10-09-2016','3','450.00');
?>

The php function array_column will come in handy here. Here is short code example that should output what you are looking for.
<?php
//Your original input
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00";
//explode the array into its sub-arrays
$arrs = explode(",", $str);
//remove the first element that sets how many elements are in each array
$numArrs = array_shift($arrs);
//convert strings into those wanted sub-arrays
array_walk($arrs, function(&$val, $key) { $val = explode(';',$val); });
//make the answer we need
$ans = array();
for($i=0; $i<$numArrs; $i++) {
//array_column does all the work that we want, making life easy
$ans[] = array_column($arrs, $i);
}
var_dump($ans);
This process does assume the string is properly formatted for what we are looking for - it will fail horribly if that is not the case.

Use the explode() function! It's really cool.
Here's how I would solve this problem. You will end up with a 2d array with my code. You can access $arr1 with $fourthStep[0] and $arr2 with $fourthStep[1] etc...
<?php
$str = "2,2;2;,1;1;,07-09-2016;07-09-2016;,08-09-2016;10-09-2016;,1;3;,100.00;450.00;";
$fourthStep = array();
//First, let's split that string up into something a little more.. readable.
$firstStep = explode(",",$str);
//$firstStep[0] contains our count for the total array count.
foreach($firstStep as $secondStep){ //Our second step is to loop through the newly created array which splits each section of your array
if ($secondStep != $firstStep[0]){ //skip the first part, as that is only telling us of array count
$thirdStep = explode(";",$secondStep); //third step is to get each data part of each section. The count of this array should be 'firstStep[0]-1'
for($i = 0; $i<$firstStep[0]; $i++){
//Now we want to assign the values into a 2D array
$fourthStep[$i][count($fourthStep[$i])] = $thirdStep[$i];
}
}
}
var_dump($fourthStep);
?>
Result:
array(2) { [0]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "08-09-2016" [4]=> string(1) "1" [5]=> string(6) "100.00" } [1]=> array(6) { [0]=> string(1) "2" [1]=> string(1) "1" [2]=> string(10) "07-09-2016" [3]=> string(10) "10-09-2016" [4]=> string(1) "3" [5]=> string(6) "450.00" } }
Just for a further note, you don't need the '2' in the first part of your string to work out how many arrays to split it into, as they use 2 different seperators you can work it out quite easily. Save like 8 bits of space or somethin'

Related

Difference between two arrays containing numbers as string

I´ve got a question about compairing two (text)arrays. I obtained two arrays from a loop containing numbers as shown below:
array(96) { [1]=> string(2) "20" [2]=> string(2) "18" [3]=> string(2)...
array(96) { [1]=> string(3) "135" [2]=> string(3) "103" [3]=> string(2) "88"
What I want is a new array which contains the difference of the values (1-2). This means that the 2 arrays above will results in the following new (text)array
array(96) { [1]=> string(3) "-115" [2]=> string(3) "-85" [3]=> string(2)
Can someone help me?
You could do this with one foreach-loop. And then substract them from each other. You just need the same count of elements in $array and in $array2.
$new = array();
foreach($array as $key => $val) {
$new[] = (string) ($val - $array2[$key]);
}
If it doesn't matter if the values are integers, you can remove the type casting (string).
this is a function,
function foo($array1, $array2){
$resultArray = array();
for($i=0; i<count($array1); $i++){
$resultArray[] = (string)((int)$array1[$i] - (int)$array2[$i]);
}
return $resultArray;
}
Hope this will help :)
<?php
$a=array(20,18);
$b=array(135,103);
function fr($d,$d1){
global $c;
$c[]=$d-$d1;
}
array_map('fr',$a,$b);
var_dump($c);

php regex to match key value pairs

I have a string like as below.
$string = "height=175cm weight=70kgs age=25yrs"
String contents are key value pairs each pair are separated by a Tab. I want each key value pairs as separate variable and prints out each.
I have tried with below code but i am not getting proper result please help me where i went wrong.
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "(([^=]*)\s*=\s*(.*))";
if (preg_match($pattern,$string,$match)) {
echo "<pre>";
print_r($match);
} else {
echo "not matche\n";
}
Result:
Array
(
[0] => height=175cm weight=70kgs age=25yrs
[1] => height
[2] => 175cm weight=70kgs age=25yrs
)
You can use this code:
$string = "height=175cm weight=70kgs age=25yrs";
if (preg_match_all('/\s*([^=]+)=(\S+)\s*/', $string, $matches)) {
$output = array_combine ( $matches[1], $matches[2] );
print_r($output);
}
OUTPUT:
Array
(
[height] => 175cm
[weight] => 70kgs
[age] => 25yrs
)
You can use this:
$string = "height=175cm weight=70kgs age=25yrs";
$pattern = "/(\w+)=(\d+)(\w+)/i";
if(preg_match_all($pattern,$string,$match))
{
var_dump($match);
}
Result:
array(4) {
[0]=>
array(3) {
[0]=>
string(12) "height=175cm"
[1]=>
string(12) "weight=70kgs"
[2]=>
string(9) "age=25yrs"
}
[1]=>
array(3) {
[0]=>
string(6) "height"
[1]=>
string(6) "weight"
[2]=>
string(3) "age"
}
[2]=>
array(3) {
[0]=>
string(3) "175"
[1]=>
string(2) "70"
[2]=>
string(2) "25"
}
[3]=>
array(3) {
[0]=>
string(2) "cm"
[1]=>
string(3) "kgs"
[2]=>
string(3) "yrs"
}
}
I've pasted a code sample below which helps you to solve your problem. Certainly, it is not very tightly compressed and has quite a few more lines of code than the other answers (which are all good answers!).
The reason I did this was because it looks like you may benefit from an explanation that takes you one step at a time in the progression of solving your problem, so that you can understand what is happening along the way.
Here's the code you can use:
<?php
$string = "height=175cm\tweight=70kgs\tage=25yrs";
// Divide your string into an array, with each element
// in the array being a string with a key-value pair
$pairs = explode("\t", $string);
// See what the array of pair strings looks like.
// print_r($pairs);
// Create an array to get it ready to hold key-value pairs.
$results = array();
// For each string in your array, split at the equal sign
// and set values in the $results array.
foreach ($pairs as $pair) {
$exploded_pair = explode("=", $pair);
// See what each exploded pair array looks like.
// print_r($exploded_pair);
$key = $exploded_pair[0];
$value = $exploded_pair[1];
$results[$key] = $value;
}
print_r($results);
Instead of using regular expressions, this makes use of the explode function in PHP. You can read the documentation on explode found here.
You said that your input string is separated by tabs, which is why the assignment statement for $string has \t instead of spaces. If you were to use spaces instead of tabs, then make sure that you change
$pairs = explode("\t", $string);
to
$pairs = explode(" ", $string);

Creating an associative array with strings

I read some words from a text file, storing each word as an array element using the file() function. Now I need to sort each word and create an associative array that stores the sorted strings as keys and the original strings as values like so :
$hash_table = array( 'sorted_string' => 'original string' );
I loop through every word read from the file and sort it in ascending order but when it comes to pushing it to the associative array, I am completely lost. Can anyone show me how to create the associative array ?
$a = array('green', 'yellow', 'red');//actual
$b = array('green', 'yellow', 'red');
sort($b); //sorted
$c = array_combine($b, $a);
If I understand your question right, consider this:
$sorted; //sorted array
$original; //original array
foreach($sorted as $key){
$index = 0;
$new_array[$key] = $original[$index++];
}
Here is what you want:
<?php
//create an array with words, similar to what you get with file()
$str = "here is a list of random words that will be sorted";
$array = explode(" ", $str);
//a place to store the result
$result = array();
//check each value
foreach($array as $word) {
//str_split will create an array from a string
$letters = str_split(trim($word));
//sort the letters
sort($letters);
//implode the letters again to a single word
$sorted = implode($letters);
//add to result
$result[$sorted] = $word;
}
//dump
var_dump($result);
//sort on the key
ksort($result);
//dump
var_dump($result);
?>
This will output
//unsorted
array(11) {
["eehr"]=>
string(4) "here"
["is"]=>
string(2) "is"
["a"]=>
string(1) "a"
["ilst"]=>
string(4) "list"
["fo"]=>
string(2) "of"
["admnor"]=>
string(6) "random"
["dorsw"]=>
string(5) "words"
["ahtt"]=>
string(4) "that"
["illw"]=>
string(4) "will"
["be"]=>
string(2) "be"
["deorst"]=>
string(6) "sorted"
}
//sorted on key
array(11) {
["a"]=>
string(1) "a"
["admnor"]=>
string(6) "random"
["ahtt"]=>
string(4) "that"
["be"]=>
string(2) "be"
["deorst"]=>
string(6) "sorted"
["dorsw"]=>
string(5) "words"
["eehr"]=>
string(4) "here"
["fo"]=>
string(2) "of"
["illw"]=>
string(4) "will"
["ilst"]=>
string(4) "list"
["is"]=>
string(2) "is"
}

PHP Array, Move Elements [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I am creating an array from several text boxes. I am needing to move the elements in the array to insert into the database. Here is the array:
array(2) { [0]=> string(7) "nameone" [1]=> string(7) "nametwo" }
array(2) { [0]=> string(6) "ageone" [1]=> string(6) "agetwo" }
array(2) { [0]=> string(13) "parentnameone" [1]=> string(13) "parentnametwo" }
array(2) { [0]=> string(14) "parentemailone" [1]=> string(14) "parentemailtwo" }
array(2) { [0]=> string(14) "parentphoneone" [1]=> string(14) "parentphonetwo" }
I want to end up with an insert statement such as:
nameone, ageone, parentnameone, parentemailone, parentphoneone
and next row to insert would be
nametwo, agetwo, parentnametwo, parentemailtwo, parentphonetwo
I have tried to create an array with multiple for each loops but I end up with an array that i need to move the keys which brings be back to my original problem.
Is there a method to this madnaess?
Well, lets say your main array contains 5 arrays with 2 elements each. Lets call that $mainArr. "2" in the first line is no. of elements in each subarray. or if the subarraays are not of equal lengths, then the its the length of the largest subarray.
for($i=0;$i<2;$i++) {
foreach($mainArr as $key => $a) {
$ins[$i][] = $a[$i];
} // form an array with insert elements
}
// traverse that to form inserts
foreach($ins as $key => $arr) {
$statements[] = implode(",", $ins[$key]);
}
echo '<pre>';
print_r($statements);
I think thats what you want. If not, let me know. Hope that helps!
$l = count($array[0]);
for ($i=0; $i<$l; $i++) {
// access values like this:
$name = $array[0][$i]; // equals nameone first time and nametwo second time
$age = $array[1][$i];
$parentname = $array[2][$i];
$parentemail = $array[3][$i];
$parentphone = $array[3][$i];
// insert into DB here
}
#!/usr/bin/php
<?php
$val = array('name', 'age', 'parentname', 'parentemail');
$key = array('one', 'two', 'three', 'four', 'five');
$valone = array();
foreach ($val as $k)
array_push($valone, $k.$key[0]);
var_dump($valone);
?>
Outputs :
array(4) {
[0]=>
string(7) "nameone"
[1]=>
string(6) "ageone"
[2]=>
string(13) "parentnameone"
[3]=>
string(14) "parentemailone"
}
Is this what you want you to do ?

php json decode result in another json decode

I have 2 json data from nosql. first match if the search word match in $array1, get the item number then put item number into $array2, get the price of custom search require. But my code cause Invalid argument supplied for foreach() in
foreach($json2[$num] as $data2)
$str = 'paper';
$array1 = '[{"a":"1","b":"book"},{"a":"2","b":"paper"}]';
$array2 = '[{"1":["17.00","22.00"]},{"2",["4.50","6.00"]}]';
$json1 = json_decode($array1);
$json2 = json_decode($array2,true);
foreach($json1 as $data1){
if(preg_match('#'.$data1->b.'#',$str,$match)){
$num = $data1->a; // $num = 2
}
}
foreach($json2[$num] as $data2){
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
First off your JSON for $array2 is not valid. It should be:
[{"1":["17.00","22.00"]},{"2":["4.50","6.00"]}]
-----------------------------^
This should be a ":", not a ","
Your JSON is actually an array of objects (arrays). var_dump($json2); shows this.
array(2) {
[0]=>
array(1) {
[1]=>
array(2) {
[0]=>
string(5) "17.00"
[1]=>
string(5) "22.00"
}
}
[1]=>
array(1) {
[2]=>
array(2) {
[0]=>
string(4) "4.50"
[1]=>
string(4) "6.00"
}
}
}
You're gonna need to loop over it like this:
foreach($json2 as $data2){
if(array_key_exists($num, $data2)){
$data2 = $data2[$num];
foreach($data2 as $newdata){
echo $newdata.'<br />'; // 4.50, 6.00
}
}
}
If $num = 2 in your comments is correct, you'll be accessing the third element in $json2 but you can't since there only are two.
Update
Oops, how did I miss this? Your $array2 already has the indices right there, you're just not loading them properly. You can simply loop through $array2 and look for the key. However, a better solution would be to load the data properly, by filling $array2 as a dictionary rather than a list.

Categories