2

This is my form input $data, i want this keep this input.

$data = "39X3,29X5";

this my code convert string to array

$data = explode(",", $data);

$out = array();
$step = 0;

foreach($data as $key=>$item){
   foreach(explode('X',$item) as $value){
   $out[$key][$step++] = $value;
}
print '<pre>';
print_r($out);
print '</pre>';

result

Array
(
    [0] => Array
    (
        [0] => 39
        [1] => 3
    )

    [1] => Array
    (
        [2] => 29
        [3] => 5
    )
)

but i want change the keys and fix this for support query builder class

$this->db->insert_batch('mytable',$out). 

Like this.

array
(
    array
    (
        'number' => 39
        'prize' => 3
    ),
    array
    (
        'number' => 29
        'prize' => 5
    )
)

i try hard and confuse using loop.

2
  • foreach(explode(",", $data) as $item) { $out[] = array_combine(['number', 'prize'], explode('X',$item)); } Commented Dec 6, 2018 at 13:41
  • thanks, this worth. i don't belive it's so simple Commented Dec 6, 2018 at 23:00

2 Answers 2

2

So you need to remove inner foreach and put relevant values into array.

foreach($data as $key=>$item){
    $exp = explode('X', $item);
    $out[$key] = [
        'number' => $exp[0],
        'prize' => $exp[1]
    ];
} 

Check result in demo

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

2 Comments

if i insert $data = "39,29X5"; this will error Notice: Undefined offset: 1 in /in/Y715I on line 9 but still viewed. how to remove this notice. check result in demo
@AGA Use @ symbol to hide notice 3v4l.org/JqkRM
0

change your foreach loop to the following:

foreach($data as $key=>$item){
  $temp = explode('X',$item);
  $out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}

Comments

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.