0

I've been trying to do it for a few hours now but i don't have any specific idea. I would like to achieve such a result as shown below. The array is derived from a json file.

I have:

[0] => Array(
    [Id] => scr_1 
    [Size] => 1920, 1080
)
[1] => Array(
    [Id] => scr_2 
    [Size] => 1280, 1024
)

My goal is:

[0] => Array(
    [Id] => scr_1
    [Size] => Array( 
        [Width] => 1920 
        [Height] => 1080
    )
)
[1] => Array(
    [Id] => scr_
    [Size] => Array( 
        [Width] => 1280
        [Height] => 1024
    )
)

How can I do that ? Thank you in advance!

1
  • You may use array_map or foreach Commented Sep 20, 2017 at 10:32

4 Answers 4

1
$array = array(array('Id' => 'scr_1', 'Size' => '1920, 1080'),array('Id' => 'scr_1', 'Size' => '1920, 1080'));
    foreach($array as $key => $val )
    {
        $size = explode(',',$val['Size']);
        $new['Width'] = $size[0];
        $new['height'] = $size[1];
        $array[$key]['Size'] = $new;
    }
    echo "<pre>";
    print_r($array);
    echo "</pre>";

Check this code.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to add array instead to giving string in Size key

$yourArray = array(
    array(
        "Id" => "scr_1",
        "Size" => array(
            "Width" => 1920,
            "Height" => 1080
        )
    ),
    array(
        "Id" => "scr_2",
        "Size" => array(
            "Width" => 1280,
            "Height" => 1024
        )
    )
);
$newArray = array();
foreach ($yourArray as $k => $res) {
    $newArray[$k] = array(
        "Id" => $res["Id"],
        "Size" => explode(",", $res["Size"])
    );
}

Comments

1

Try this code

<?php
    $myarray[0]["Id"] = "scr_1";
    $myarray[0]["Size"]= "1920, 1080";
    $myarray[1]["Id"] = "scr_2";
    $myarray[1]["Size"]= "1920, 1080";
    foreach($myarray as $key =>$value){
        list($width, $height) = explode(", ",$value["Size"]);
        $myarray[$key]['Size'] = array("Width"=>$width, "Height" =>$height);
    }
    echo "<pre>";print_r($myarray);
    ?>

Comments

0

Try this code:

<?php

$array = array(
    array(
        "Id" => "scr_1",
        "Size" => "1920, 1080"
    ),
    array(
        "Id" => "scr_2",
        "Size" => "1280, 1024"
    )
);

$newArray = array();

foreach ($array as $k => $v) {
    $size = explode(', ', $v['Size']);
    $newArray[$k]= array('Id' => $v['Id'],  'Size' => array('Width' => $size[0], 'Height' => $size[1]));
}   

print_r($newArray);

Comments

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.