4

I'm trying to add key names to an exploded multi-dimensional array

I've this:

    $datos = $_POST['dataGeneral'];

    // Detecting "<" delimiter and PHP_EOL:
    /* 
       1<1<Titulo Episodio<Descripción Episodio<http://www.google.com
       1<2<Titulo Episodio 2<Descripción Episodio 2<http://www.google.com 
    */

    $data = explode(PHP_EOL, $datos);
    $num = 0;

    foreach($data as &$val){
        $exp = explode("<", $val);
        $val = array_combine(range($num, $num+sizeof($exp)-1), $exp);
        $num += sizeof($exp);
    }

    echo '<pre>CheckDelimiter:<br/>';
        print_r($data);
    echo '</pre>';

Result:

enter image description here

This work fine, but I want to add keys to this array elements:

This is what I spected:

Array
(
    [post-1] => Array
        (
            [temporada] => 1
            [episodio] => 1
            [titulo] => Titulo Episodio
            [descripcion] => Descripción Episodio
            [link] => http://www.google.com
        )

    [post-2] => Array
        (
            [temporada] => 1
            [episodio] => 2
            [titulo] => Titulo Episodio 2
            [descripcion] => Descripción Episodio
            [link] => http://www.google.com
        )

)

Can you help me please?

3
  • 2
    quick note: you can't have two post keys on the same level, and you already have used the array function that you need in order to have that associative key, array_combine, just have a hardcoded array to be combined Commented Feb 19, 2016 at 1:32
  • Can you show us what the post data looks like? Commented Feb 19, 2016 at 1:33
  • $_POST added to the question. Commented Feb 19, 2016 at 1:35

1 Answer 1

2

Since you already have the base setup of the array values you need, just use array_combine again.

This time using your desired assoctive keys:

$new_data = array();
foreach($data as $k => $val){
    $exp = explode("<", $val);
    // $val = array_combine(range($num, $num+sizeof($exp)-1), $exp);
    // instead of using numeric like above
    $val = array_combine(array('temporada', 'episodio', 'titulo', 'descripcion', 'link'), $exp);
    $new_data['post-' . ($k + 1)] = $val;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Work fine, @Ghost, thanks. I'll accept the answer in 5 minutes :)
@Ferrrmolina sure glad this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.