0

So, I'm using an API that spits out info in JSON, (basically) in this format:

{"linkId":"1234asdf","clickData"
["member":{"userId":"asdf1234","email":"[email protected]","firstName":"Joe","lastName":"Schmoe"}]},
["member":{"userId":"fdsa4321","email":"[email protected]","firstName":"Moreo","lastName":"Hater"}],

--for each link in an email campaign. I want to pull this data via a nested for loop & organize it like so:

$linkCount = count($linkArray); //from previous API call

for ($i = 0; $i < $linkCount; $i++) {
    $clickReport[] = //API call here; omitted for brevity
    //parse the JSON here to get $linkid, $url; omitted for brevity
    $memberCount = substr_count($clickReport[$i],'"member":'); //to count number of people listed in JSON response
    for ($j = 0; $j < $memberCount; $j++) {
        //parse the JSON here to get $euid, $fname, $lname, $email; omitted for brevity
        $clickers[] = array (
            $euid[$i] => array (
                'fname' => $fname[$j],
                'lname' => $lname[$j],
                'email' => $email[$j],
                'links' => array (
                        'linkid' => $linkid[$i],
                        'url' => $url[i],
                ),
            ),
        );
    }
}

The issue I am having is if one member clicks more than one link, the nested for loop overwrites the previous 'links' => array(). How can I write this such that links is added to, rather than overwritten?

3
  • 2
    You are parsing the JSON? You've heard of json_encode and json_decode? Commented Jan 21, 2015 at 18:11
  • Thx @AbraCadaver -- yeah, I know those functions... but this JSON isn't actually JSON... it's stupid. It's off just enough to tick json_decode off, and I found it easier to just parse it myself rather than fix it for json_decode. Thanks for throwing that out there, though!! Commented Jan 21, 2015 at 19:18
  • @TheresaGoodlett Might be easier then to write a small function which corrects the API response to be valid JSON, if possible. Commented Jan 21, 2015 at 22:44

1 Answer 1

1

Just append to it separately.

for ($j = 0; $j < $memberCount; $j++) {
    $clickers[] = array(
        $euid[$i] => array(
            'fname' => $fname[$j],
            'lname' => $lname[$j],
            'email' => $email[$j]
        )
    );
    $euid[$i]['links'][] = array (
        'linkid' => $linkid[$i],
        'url' => $url[i],
    );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, @BadHorsie! Was helpful -- albeit just shy of perfect. :) We'll call it answered.
@kittykittybangbang Yeah sorry, I had to guess somewhat.

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.