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.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
AGA
  • 17
  • 2

2 Answers2

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • 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](https://3v4l.org/Y715I) – AGA Dec 28 '18 at 02:48
  • @AGA Use [@ symbol](https://stackoverflow.com/questions/1032161/what-is-the-use-of-the-symbol-in-php) to hide notice https://3v4l.org/JqkRM – Mohammad Dec 28 '18 at 13:56
0

change your foreach loop to the following:

foreach($data as $key=>$item){
  $temp = explode('X',$item);
  $out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}
oreopot
  • 3,392
  • 2
  • 19
  • 28