Link to home
Start Free TrialLog in
Avatar of Randy Johnson
Randy JohnsonFlag for United States of America

asked on

data conversion, array to json perhaps

I have an array like this:

["Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7"]

and I need to convert it into this:

[{
        id: "1",
        label: "Tag 1"
    }, {
        id: "2",
        label: "Tag 2"
    }, {
        id: "3",
        label: "Tag 3"
    }, {
        id: "4",
        label: "Tag 4"
    }, {
        id: "5",
        label: "Tag 5"
    }, {
        id: "6",
        label: "Tag 6"
    }, {
        id: "7",
        label: "Tag 7"
    }]


Seems easy enough but I am having trouble figuring it out.
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Use this:

$arrSrc = array("Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7");
$arrDst = array();
for ($i = 0; $i < count($arrSrc); $i++) {
    $arrDst[] = array("id " . $i + 1, "label: " . $arrSrc[$i]);
}
echo "<pre>";
var_dump($arrDst);

Open in new window

Avatar of Randy Johnson

ASKER

I need it to output on the page like I have it displayed.

I am passing back to a javascript call and doing an eval()
In JSON, line spacing does not matter outside of the tags.  http://json.org/

This appears to generate the correct JSON string.
http://www.laprbass.com/RAY_temp_rjohnsonjr.php

<?php // RAY_temp_rjohnsonjr.php
error_reporting(E_ALL);
echo '<pre>';


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28321692.html


// TEST DATA FROM THE POST AT EE
$str = <<<EOD
["Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7"]
EOD;

// MAKE AN ARRAY
$arr = json_decode($str);

// CREATE THE OUTPUT ARRAY OF OBJECTS
$out = array();

// ITERATE OVER THE ARRAY OF TAGS
foreach ($arr as $tag)
{
    // THE TAG NUMBER WILL BE USED TO CREATE THE 'id' VALUE
    $xyz = explode(' ', $tag);

    // ONE OBJECT FOR EACH TAG
    $std = new stdClass;
    $std->id = $xyz[1];
    $std->label = $tag;

    // STORE THE OBJECT IN THE ARRAY OF OBJECTS
    $out[] = $std;
}

// CREATE THE JSON STRING
$new = json_encode($out);
echo $new;

Open in new window

Best regards, ~Ray
ASKER CERTIFIED SOLUTION
Avatar of acbxyz
acbxyz
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I apologize for misunderstanding: the following code convert the array into a string.

$arrSrc = array("Tag 1","Tag 2","Tag 3","Tag 4","Tag 5","Tag 6","Tag 7");
$str = '[';
for ($i = 0; $i < count($arrSrc); $i++) {
    $str .= "{id " . $i + 1, "label: " . $arrSrc[$i])},;
}
$str = substr($str, 0, (strlen($str)-1));
$str .= "]";
echo "<pre>";
echo $str;

Open in new window

With this little change, it does:
-    $temp[] = array('id' => $id, 'label' => $label);
+    $temp[] = array('id' => ($id + 1), 'label' => $label);

Open in new window

@abcxyz: Yes, that is one of the problems of a "soft" problem definition.  Did the author really mean that the "id" property should match the number in the "label" property? Or did thie author mean that the "id" property should be numbered from 1, without regard to the number in the "label" property?  Or is this irrelevant and the "id" is a complete red herring?  There is no way to know since the author asked for one thing, then accepted something that did not match the request!  That's why I reopened it, so we can get clarification.  I'm sure the author can revisit the question. ~Ray
From reading the question verbatim it can not be done. The author wants to produce a valid output but the keys in his desired result are not quoted so it will never convert to or from a json string - just can't work.

If the author clarifies the question and be more specific I am sure they will get their answer.
The answer did match my request obviously that is why I accepted it as the answer.  I copied and pasted the code and it worked perfectly.
Ray,

Without sounding rude, how about you as the expert tell me why your solution is better than @abcxyz's solution?

Here is how I made my decision.  I clicked the email that came in with his answer first.  I saw it was 3 lines of code long.   I tried it.  It worked exactly as needed.  I then scrolled up and saw your solution.  I did not see a reason to switch out already working code.  His code was shorter and more concise.  Yes you were more thorough with your code commenting.

Unless you have some solid evidence that your solution is a better fitI am inclined to give @abcxyz the points because his solution was the most concise and works like a charm.

Thank You.
@rjohnsonjr, I don't really care which answer you accept.  The answer I posted gave the result you asked for and it was posted before the answer you accepted.  The answer you accepted did not give the answer you asked for.  The central issue is described in the post here:
https://www.experts-exchange.com/questions/28321692/data-conversion-array-to-json-perhaps.html?anchorAnswerId=39728156#a39728156

If you do not care about the relationship of the "id" and the number in the "Tag XX" data field, then naturally you would not establish a relationship by making the numbers correlate!  Indexes in PHP are naturally started from zero, and the correct output, if you do not care, might be like this:
[{
        id: "0",
        label: "Tag 1"
    }, {
        id: "1",
        label: "Tag 2" ... etc... 

Open in new window

But since you posted a request for different output in the original question, I created a response based on the understanding that you wanted the output you asked for!

For better or worse, computer programming is an activity that requires precision and meticulous attention to detail.  If someone asks for "one" and the response is "zero" that seems to misunderstand the request.

Please do whatever you think is right for your own needs and the good of the community that might one day read your question and the accepted answer.