无法将索引数组转换为关联数组在php中

huangapple go评论52阅读模式
英文:

Unable to convert indexed array to associative array in php

问题

The array $digit can be transformed into the desired form as shown below:

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

To achieve this, you can use the following code:

$newDigitsArray = [];
foreach ($digit['numbers'] as $value) {
    $newDigitsArray['numbers'][] = (int)$value;
}
\Log::info($newDigitsArray);

This code will convert the values in $digit['numbers'] from strings to integers and store them in the $newDigitsArray in the desired format.

英文:

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);

答案1

得分: 0

你可以使用内置的PHP方法 explode 来轻松实现这个功能:

$digits = ['numbers' => '1,2,3'];

$digits['numbers'] = explode(',', $digits['numbers']);

$digits

这是您提供的代码的翻译部分。

英文:

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",
    ],
  ]

>

答案2

得分: 0

你可以使用explode()函数来实现这个功能,

$digits = ['numbers' => '1,2,3'];
$digits['numbers'] = explode(',', $digits['numbers']);
print_r($digits);

输出:

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

Here you can use explode() to make this work,

$digits = ['numbers' => '1,2,3'];
$digits['numbers'] = explode(',', $digits['numbers']);
print_r($digits);

Output :

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

答案3

得分: -1

请尝试这段代码:

$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>';

这是您提供的代码的中文翻译部分。

英文:

Try this code:

$digit = array();
$digit[&#39;numbers&#39;] = array(1,2,3,4,5,6);
    
foreach($digit[&#39;numbers&#39;] as $k =&gt; $v){
    $num[] = $v;
}
    
$neo_digit[&#39;numbers&#39;] = $num;
    
echo &#39;&lt;pre&gt;&#39;.print_r($neo_digit, true).&#39;&lt;/pre&gt;&#39;;

huangapple
  • 本文由 发表于 2023年7月4日 21:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定