Laravel Input::old is an array as a string - php

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);
}
?>

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;
}

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);
}

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))) {
}

Related

Remove Quotes from object using php

I have a json object.In that i need to remove double quotes.
{"1":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"},"2":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"},"3":{"1":"{m:4,preference:1,r:0,tt:0}","2":"{m:4,preference:1,r:0,tt:0}","3":"{m:4,preference:1,r:0,tt:0}"}}
I need to remove the Quotes from object.
{"1":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}},"2":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}},"3":{"1":{m:4,preference:1,r:0,tt:0},"2":{m:4,preference:1,r:0,tt:0},"3":{m:4,preference:1,r:0,tt:0}}}
I tried :
json_decode($request),json_decode(json_encode($request))
but no result.it returns null.
Also i need to add quotes to keys
{"m":4,"preference":1,"r":0,"tt":0}
You need first to try make valid json on sender. But if you can't, use below code to manually parse source string $str
function like_json_decode($str) {
$arr = array_map('trim', explode(',', $str));
$new_arr = [];
foreach ($arr as &$x) {
$x = trim($x, ' {}');
$x = array_map('trim', explode(':', $x));
$new_arr[$x[0]] = $x[1];
}
return $new_arr;
}
$arr = json_decode($str, true);
foreach ($arr as &$subarr) {
foreach($subarr as &$x) {
$x = like_json_decode($x);
}
}
print_r($arr);
demo

How to get PHP value from input using Tagify

I have a problem with submitting a PHP form using jQuery Tagify.
If I add 2 tags like John and Thomas, then I'm getting $_POST['tag'] as:
'[{"value":"John"}, {"value":"Thomas"}]'
How I can change my $_POST['tag'] to get this POST as: John,Thomas?
var_dump(implode(', ', array_column(json_decode($_POST['tag']), 'value')));
First you decode the JSON coming in $_POST['tag'] into an array/object structure. array_column gives you the flat array with the values. Then you join it separated by commas (implode).
Yes, the square brackets is in the way. In fact, tagify-js outputs an array of json objects. So json_decode function doesn't work either. It is necessary to prepare the output.
Here is the function I implemented to save the input value. It converts them to an array of values.
function br_bookmarks_tagify_json_to_array( $value ) {
// Because the $value is an array of json objects
// we need this helper function.
// First check if is not empty
if( empty( $value ) ) {
return $output = array();
} else {
// Remove squarebrackets
$value = str_replace( array('[',']') , '' , $value );
// Fix escaped double quotes
$value = str_replace( '\"', "\"" , $value );
// Create an array of json objects
$value = explode(',', $value);
// Let's transform into an array of inputed values
// Create an array
$value_array = array();
// Check if is array and not empty
if ( is_array($value) && 0 !== count($value) ) {
foreach ($value as $value_inner) {
$value_array[] = json_decode( $value_inner );
}
// Convert object to array
// Note: function (array) not working.
// This is the trick: create a json of the values
// and then transform back to an array
$value_array = json_decode(json_encode($value_array), true);
// Create an array only with the values of the child array
$output = array();
foreach($value_array as $value_array_inner) {
foreach ($value_array_inner as $key=>$val) {
$output[] = $val;
}
}
}
return $output;
}
}
Usage:
br_bookmarks_tagify_json_to_array( $_POST['tag'] );
Hope it helps others.

The best way to strip out tag of multidimensional array in php

I have a form that send a 3 dimensional array to a controller through a POST method. In that controller, I need to strip out the content of each element inside my 3D POST variable, with the php built in function strip_tags($variable)
What is the best solution.
I tried the following code, but I get an empty post variable at the end:
$temp = array();
function stripTags($v, $k)
{
if ($v != 'preferences' && $v != 'title'):
$temp[$v] = strip_tags($k);
else:
$temp[$v] = $k;
endif;
}
//Clean up the $_POST
if (is_array($_POST)):
array_walk_recursive($_POST, 'stripTags');
$_POST = $temp;
endif;
From the strip_tags documentation comments:
function strip_tags_deep($value)
{
return is_array($value) ?
array_map('strip_tags_deep', $value) :
strip_tags($value);
}
// Example
$array = array('<b>Foo</b>', '<i>Bar</i>', array('<b>Foo</b>', '<i>Bar</i>'));
$array = strip_tags_deep($array);
// Output
print_r($array);

Add element to array then encode it to json

I have this code
$data['events'] = $this->calendar_model->get_events();
foreach ($data['events'] as $arr) {
settype($arr,"array");
$arr['something'] = false;
//print_r($arr);
}
echo json_encode($arr);
what I am trying to do is to add something => false to each record of the array
so lets say I got from the database
array of
title:"aaaaa",
start: "xxxx",
end: "cccc",
I want to add to each one something :false to become like
title:"aaaaa",
start: "xxxx",
end: "cccc",
something,false
for each record
but the problem is when I print using the print_r its fine, but the json_encode print only the last one.
Passing by value vs. by reference
You are passing your $arr by value in your foreach loop. Try to pass it by reference.
This is done by adding a & just before your $arr variable in your loop declaration:
foreach ($data['events'] as &$arr) {
settype($arr,"array");
$arr['something'] = false;
}
echo json_encode($data['events']);
How it works
Passing by value means that your foreach loop instanciates a local copy or your array. All modifications made inside the loop will affect only the local copy.
Passing by reference means that inside your loop, you are working directly on the original array. But be careful when doing that because it can be dangerous. For instance, I don't know what are the consequences of calling setType($arr,"array"); for the rest of your code.
You're not collecting $arr from each iteration of your loop into anything. It looks like you probably want to push $arr onto another array that stores everything, and then JSON encode that new array.
Try this:
$collection = array();
$data['events'] = $this->calendar_model->get_events();
foreach ($data['events'] as $arr) {
settype($arr,"array");
$arr['something'] = false;
array_push($collection, $arr);
}
echo json_encode($collection);
$data['events'] = $this->calendar_model->get_events();
foreach ($data['events'] as &$arr) {
settype($arr,"array");//This if there is not array
$arr['something'] = false;
}
echo json_encode($data['events']);
Try to make your own json like this
$strJson = '';
$data['events'] = $this->calendar_model->get_events();
foreach ($data['events'] as $arr) {
settype($arr,"array");
$arr['something'] = false;
//Assign value as yours in blow code
$strJson .= '{"title" : "'.$arr.'","start" : "'.$arr.'","end" : "'.$arr.'"},';
}
$strJson1=rtrim($strJson, ",");
$newStr = '['.$strJson1.']';
echo $newStr;

Remove value from array based on value?

I have a PHP array with a parent called "items." In that array, I want to remove all values that do not contain a string (which I'm gonna use regex to find). How would I do this?
foreach($array['items'] as $key=>$value) { // loop through the array
if( !preg_match("/your_regex/", $value) ) {
unset($array['items'][$key]);
}
}
You can try using array_filter.
$items = array(
#some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
return preg_match($regex, $a) !== 0;
});
NOTE: This only works in PHP 5.3+. In 5.2, you can do it this way:
function checkStr($a){
$regex= '/^[some]+(regex)*$/i';
return preg_match($regex, $a) !== 0;
}
$items = array(
#some values
);
$items = array_filter($items, 'checkStr');

Categories