0

I have two arrays (below). Is it possible to convert them into json string?

Array
        (
            [0] => size
            [1] => color
        )
Array
        (
            [0] => L
            [1] => Black
        )

Output structure should be:

[
   {"name":"size","value":"L"},
   {"name":"color","value":"Black"}
]

Thanks!

3
  • 2
    Wut ? Have you searched json_encode()? Commented May 2, 2013 at 8:21
  • 1
    Split your task into 2 simpler ones: 1: to combine 2 arrays into a single one with a proper structure 2. To generate json. That's how we all solve our issues every day. Commented May 2, 2013 at 8:22
  • Array combine return me this Array ( [size] => L [color] => Black ) Commented May 2, 2013 at 8:24

5 Answers 5

2

Sure:

$array1 = array('size', 'color');
$array2 = array('L', 'Black');

$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
    $jsonArray[] = array('name' => $name, 'value' => $value);
}

echo $json = json_encode($jsonArray);

This gives you

[{"name":"size","value":"L"},{"name":"color","value":"Black"}]
Sign up to request clarification or add additional context in comments.

1 Comment

$jsonArray = array(); foreach (array_combine(array_keys($product["option"]["name"]), array_values($product["option"]["name"])) as $name => $value) { $jsonArray[] = array('name' => $name, 'value' => $value); } $json = json_encode($jsonArray);
0

this here should work:

$json = json_encode( array_combine( $array1, $array2 ) );

2 Comments

Result is: {"size":"L","color":"Black"}
I need: {"name":"size","value":"L"}, {"name":"color","value":"Black"}
0

Something like this should work just how you want:

<?php
    $keys = array("size", "color");
    $values = array("L", "Black");

    $array = array();
    foreach ($keys as $i => $key) {
        $array[] = array(
            "name" => $key,
            "value" => $values[$i]
        );
    }

    $json = json_encode($array);

    var_dump($json);

    //string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>

Comments

0
    $array1 = array('size', 'color');
    $array2 = array('L', 'Black');

    $result = array_combine($array1 , $array2);
    $json = array();
    foreach($result as $key => $val){
     $json[] = array('name' => $key, 'value' => $value);
    }
    $json = json_encode($json);

1 Comment

:) I don't know keys and values (eg. size or color)
0

I think you are looking for this:

$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
   {
    $array3[]=array($array1[$i]=>$array2[$i]);
    }
echo json_encode($array3);

?>

Output:

[{"size":"L"},{"color":"Black"}]

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.