How to separate string in array?

Asked

Viewed 541 times

1

I have a column descri_produto which would be the product description.

The problem is that I am not able to separate the description in array.

$cat = $_POST['categoria'];
$sql= "SELECT DISTINCT descri_produto, cat_produto FROM produtos WHERE cat_produto  LIKE '".$cat."'";
$result= mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)){
        print_r(explode(',',$row['descri_produto']));
    }
}

Example row of the product description column

Espessura: 6mm,Cor: Incolor

At the moment it’s returning:

Array
(
    [0] => Espessura: 6mm
    [1] => Cor: Incolor 
)

and I need something like:

Array
(
    [Espessura] =>  6mm
    [Cor] => Incolor 
)
  • You can play in another array the position 0 as key and the position 1 as value. $arr1 = explode(',',$row['descri_produto']); and then $arr2 = array($arr1[0]=>$arr1[1])

2 answers

1


You have to break into 2 parts, first break each field, as you are doing, then break each field into key / value and put into an array. created a function that does this, just pass the text that comes from Mysql and it returns you the array in the format you need.

function quebra($descricao) {
    $campos = explode(',', $descricao);

    $array = [];

    foreach ($campos as $campo) {
        // o terceiro parametro do explode eh o numero maximo de valores
        // que o explode vai quebrar (2), se por acaso tiver no seu valor outro ':'
        list($chave, $valor) = explode(':', $campo, 2);

        // remove espacos extras
        $chave = trim($chave);
        $valor = trim($valor);

        $array[$chave] = $valor;
    }

    return $array;
}


$quebrado = quebra('Espessura: 6mm,Cor: Incolor');
var_dump($quebrado);

That code will print:

array(2) {
     ["Espessura"]=> string(3) "6mm"
     ["Cor"]=>  string(7) "Incolor"
}
  • Thank you very much, everything came out right

1

You can do it like this:

$cat    = $_POST['categoria'];
$sql    = "SELECT DISTINCT descri_produto, cat_produto FROM produtos WHERE 
cat_produto  LIKE '".$cat."'";
$result = mysqli_query($conn, $sql);
$data   = [];

if (mysqli_num_rows($result) > 0){
    while ($row = mysqli_fetch_assoc($result)){
        $_items = explode(',',$row['descri_produto']);
        foreach ( $_items as $item ) {
            $_data = explode(':', $item);
            $data[strtolower($_data[0])] = $_data[1];
        }
    }
}

echo '<pre>';
print_r($data);
die;

// Retorno do data
Array
(
    [espessura] =>  6mm
    [cor] =>  Incolor
)
  • Thank you gave everything right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.