1

I have the following text string

Liane Lanford$310.40$0.00$325.92 Ken Christenson$134.75$0.00$141.49 Melissa Jaramillo$951.78$0.00$999.37

I need to create an array so that i can insert the data into mysql database in the following format

enter image description here

I tried to do it using explode but stacked at Ken Christenson and Melissa Jaramillo. And complexity is there may be 3, 4 five or more customer instead of 3. How can i do this in php.

1
  • 2
    Could you post the code you tried? Commented Jan 7, 2020 at 17:20

1 Answer 1

1

you could split it with regex:

preg_match_all('/ ?([^\$]+)(\$[0-9\.,]+)(\$[0-9\.,]+)(\$[0-9\.,]+)/i',$str,$results);

the $results array would contain the full match at index 0, followed by name, subtotal, holdback, total:

[
  [
    "Liane Lanford$310.40$0.00$325.92",
    " Ken Christenson$134.75$0.00$141.49",
    " Melissa Jaramillo$951.78$0.00$999.37"
  ],
  [
    "Liane Lanford",
    "Ken Christenson",
    "Melissa Jaramillo"
  ],
  [
    "$310.40",
    "$134.75",
    "$951.78"
  ],
  [
    "$0.00",
    "$0.00",
    "$0.00"
  ],
  [
    "$325.92",
    "$141.49",
    "$999.37"
  ]
]

for the insert part (that you asked in the comments), try this:

try this instead:

for ($i=0;$i<count($array[0]);$i++) {
    mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('" . $array[0][$i] . "','" . $array[1][$i] . "','" . $array[2][$i] . "','" . $array[3][$i] . "') ");
}

but keep in mind that the values should be checked & escaped. if any name contains an ' , the query will fail

Sign up to request clarification or add additional context in comments.

4 Comments

Perfect. could store it to array and now trying to store that into database as preg_match_all('/ ?([^\$]+)(\$[0-9\.]+)(\$[0-9\.]+)(\$[0-9\.]+)/i',$cus_block_string,$results); echo "<pre>"; $array = array_slice($results,1); print_r($array); echo "</pre>"; foreach ($array as $payment_type => $payment) { foreach ($array[payment_type] as $pay => $value) { mysqli_query($link, "INSERT INTO table(name,subtotal,holdback,total) VALUES ('$pay[0]','$pay[1]','$pay[2]','$pay[3]') "); } } I think i am not doing it right. Can u please help? Thanks
Kim Ward$541.30$0.00$611.67 Kim Ward$784.25$0.00$886.20 Kim Ward$1,807.45$0.00$2,042.42 for this string it is truncating the last data showing first 2 Kim Ward only
it's because of the commas in the numbers - i updated my answer accordingly (the regex changed - update the line with the command preg_match_all in your code)
Thanks a lot. Its perfect now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.