ONYX
ONYX

Reputation: 5859

Laravel Input::old is an array as a string

In my form im outputting some json or a string of data that is an array from Input::old('tags') the problem I'm having is being able to test it and see if it is json and if it is do a foreach loop and put the tag attribute is an array then implode the array and output it in an input field.

[{"id":112,"tag":"corrupti","tagFriendly":"corrupti","created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28","pivot":{"question_id":60,"tag_id":112,"created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28"}},{"id":9,"tag":"placeat","tagFriendly":"placeat","created_at":"2015-07-20 00:05:23","updated_at":"2015-07-20 00:05:23","pivot":{"question_id":60,"tag_id":9,"created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28"}}]

So my output should look like this

'corrupti, placeat, etc...'

Could someone help me get the desired result following the steps I just outlined

This code doesn't work but it's what I kinda need to happen. is_array is always false

<?php
    $tags = Input::old('tags');
    if(is_array($tags)) {
        foreach ($tags as $tag) {
            $tags[] = $tag->tag;
        }
        $tags = implode(', ', $tags);   
    }                       
?>

Upvotes: 0

Views: 3403

Answers (3)

GeorgeQ
GeorgeQ

Reputation: 1382

Here you go.

$tags = json_decode(Input::old('tags'), true); // decode json input as an array

if (is_array($tags)) {
    foreach ($tags as $key=>$value) {
        $tags[$key] = $value['tag'];
    }
    $tags = implode(', ', $tags);
    echo $tags;
}

Upvotes: 3

askilondz
askilondz

Reputation: 3294

Try adding true to json_decode.

json_decode($tags, true);

According to the docs that should return an associative array. http://php.net/manual/en/function.json-decode.php

is_array might not work with associative arrays with a key/value pair. Try replacing is_array with this function:

function is_associate_array($array)
{
    return $array === array_values($array);
}

So:

if(is_associate_array(json_decode($tags, true))) {

}

Upvotes: 1

rotvulpix
rotvulpix

Reputation: 466

You can use array_map to extract the tag property from the object.

<?php
$jsonObject = json_decode(Input::old('tags'));
if(is_array($jsonObject)) {
    $onlyTags = array_map(function($item) { return $item->tag; },$jsonObject);
    print implode(",", $onlyTags);
}

Upvotes: 1

Related Questions