在php中,如何将特定类型的字符串转换为带有键的数组?
我有一个这种类型的字符串:在php中,如何将特定类型的字符串转换为带有键的数组?,php,arrays,string,checkbox,Php,Arrays,String,Checkbox,我有一个这种类型的字符串: string(11) "2=OK, 3=OK" 从文本文件。但我想将其转换为这种类型的密钥数组: array ( [2] => Ok [3] => Ok ) 我想知道我们如何在PHP中做到这一点 注意:-我通常使用explode和STRU split将字符串转换为数组,但在这种情况下,我不知道如何进行转换。您可以使用默认文件读取代码并遍历它以实现所需的转换 $temp = []; if ($fh = fopen('demo.txt', 'r')
string(11) "2=OK, 3=OK"
从文本文件。但我想将其转换为这种类型的密钥数组:
array (
[2] => Ok
[3] => Ok
)
我想知道我们如何在PHP中做到这一点
注意:-我通常使用explode和STRU split将字符串转换为数组,但在这种情况下,我不知道如何进行转换。您可以使用默认文件读取代码并遍历它以实现所需的转换
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
-将用户提供的函数应用于阵列的每个成员
-将回调应用于给定数组的元素
-用一个字符串拆分一个字符串
按“,”符号分解字符串。您将得到一个类似['2=OK','3=OK']的数组
使用foreach修剪并按“=”符号分解每个元素
使用,连同
您可以将preg\u match\u与数组\u combine、str\u word\u count一起使用
输出
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
到目前为止你都尝试了什么?一个好的开始是看explode。我通常使用explode和str_split将字符串转换为数组,但在这种情况下,我不知道怎么做。
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)