In addition to the mandatory approaches presented in the other responses, it is also possible to use a functional approach using the function array_reduce()
, which reduces an array to a single value via an iterative process via callback, in this case exploding each element of the original array and recombining the fragments in an associative array.
Another way is with array_reduce()
dividing the original array in two, one containing the keys the other the values, and combining them in an associative array with the function array_combine
.
<?php
$dadosCli1 = array("cep:'000000'", "cidade: 'sao paulo'", "rg: '00.000.000.-00'", "estado: 'sp'");
$dadosCli2 = array("rg:'11.111.111.-11'", "cidade: 'campo grande'", "cep: '0000000'", "estado: 'ms'");
$res1 = array_reduce($dadosCli1, function($c, $i){
$v = explode(':', $i, 2);
$c[$v[0]] = $v[1];
return $c;
}, []);
$res2 = array_combine(...array_reduce($dadosCli2, function($c, $i){
$v = explode(':', $i, 2);
$c[0][] = $v[0];
$c[1][] = $v[1];
return $c;
}, [[],[]]));
echo $res1["cidade"]; //'sao paulo'
echo $res2["cidade"]; //'campo grande'
Test the code on Repl.it
The above solutions in function form:
function f1($arr){
return array_reduce($arr, function($c, $i){
$v = explode(':', $i, 2);
$c[$v[0]] = $v[1];
return $c;
}, []);
}
function f2($arr){
return array_combine(...array_reduce($arr, function($c, $i){
$v = explode(':', $i, 2);
$c[0][] = $v[0];
$c[1][] = $v[1];
return $c;
}, [[],[]]));
}
Use in the third parameter of explode the value 2 (ex:
explode(':', $val, 2)
), to avoid splitting the string into more pieces, if there is a ":" inside something, for example"'foo':'bar:baz'"
... of course in the author’s current code seems expendable, but you can’t be sure :)– Guilherme Nascimento
@Guilhermenascimento was in doubt whether the answer would be a palliative or a gambiarra to solve the problem rs. Your suggestion closes all loose ends rsrsrs []’s
– Papa Charlie