skip to Main Content

The array $digit now has data in this form :

'numbers' => 
  array (
    0 => '1,2,3',
  )

But I need that array in the below shown form:

'numbers' => 
  array (
    0 => 1,
    1 => 2,
    2 => 3,
  ),

How to achieve this?

I tried the below things. But all those are returning data in same form as I currently have .Any help is appreciated.

Method 1:

$newDigitsArray=[];
$i=0;
foreach( $digit[$i] as $key =>$value) { 
    $newDigitsArray['numbers']= [$i => $value];
    $i++;
}
Log::info($newDigitsArray);

Method 2:

$newDigitsArray=[];
for($i=0;$i<count($digit);){
    $newDigitsArray[$i]=$digit[$i];
    $i++;
}
 Log::info($newDigitsArray);

2

Answers


  1. You can use the built-in php method explode to achieve this easily:

    > $digits = ['numbers' => '1,2,3']
    = [
        "numbers" => "1,2,3",
      ]
    
    > $digits['numbers'] = explode(',', $digits['numbers'])
    = [
        "1",
        "2",
        "3",
      ]
    
    > $digits
    = [
        "numbers" => [
          "1",
          "2",
          "3",
        ],
      ]
    
    >
    
    Login or Signup to reply.
  2. Try this code:

    $digit = array();
    $digit['numbers'] = array(1,2,3,4,5,6);
        
    foreach($digit['numbers'] as $k => $v){
        $num[] = $v;
    }
        
    $neo_digit['numbers'] = $num;
        
    echo '<pre>'.print_r($neo_digit, true).'</pre>';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search