$session_activity_category = array();
foreach($search_venue as $venue_b) {
$session_activity_category[] = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
}
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode(array('activity_category'=>$session_activity_category,'activity'=>$session_activity,'activity_session'=>$search_session,'activity_venue'=>$search_venue),JSON_UNESCAPED_SLASHES)
);
I want to remove the arrays given in the arrow lines
Convert the JSON to the array. Then just create a new array with the same key active category (in my example, something):
<?php
$json = '
{"something": [[
{
"blah": "blah"
},
{
"blah": "blah"
}
]]}
';
$array = json_decode($json, true);
$array = [
"something" => $array['something'][0],
];
echo json_encode($array);
Which will output:
{"something":[{"blah":"blah"},{"blah":"blah"}]}
Seems that $this->users_model->search_categories_by_session($venue_b->activity_venue_id) returns array of objects. You should parse this objects to the $session_activity_category array each iteration of search_categories_by_session function call.
$session_activity_category = array();
array_walk($search_venue, function($venue_b) use (&$session_activity_category) {
$categories = $this->users_model->search_categories_by_session($venue_b->activity_venue_id);
foreach ($categories as $category) {
$session_activity_category[] = $category;
}
});
Related
I am trying to search array values in key of associative array and then make and array of key values. I a using in_array() func to search but i can use foreach func for one array.
This is my code, but the issue is it asks me for string and I gave array.
function getrarity(){
$json = '{"cards":[
{
"card_verify_id":"1",
"name":"cardname1",
"rarity":"1"
},
{
"card_verify_id":"2",
"name":"cardname2",
"rarity":"2"
}]
}';
$card = array(1, 2);
$cards = json_decode($json);
$commons = array();
foreach($cards->cards as $items) {
if(in_array($card, $items->card_verify_id)){
$commons[] = array("$items->card_verify_id", "$items->name", "$items->rarity");
}
}
return $commons;
}
print_r(getrarity());
That's because in_array doesn't take an array as the first argument. You can simply filter and check if card_verify_id is in $card. Decoding as an array:
$cards = json_decode($json, true)['cards'];
$commons = array_filter($cards,
function($v) use($card) {
return in_array($v['card_verify_id'], $card);
});
Decoding as an object:
$cards = json_decode($json)->cards;
$commons = array_filter($cards,
function($v) use($card) {
return in_array($v->card_verify_id, $card);
});
I need to have data output in a very specific format to be used with something.
$product = Product::with('product_attribute_values', 'product_attribute_values.product_attribute_key')->find(2);
$product_decoded = json_decode($product, true);
I need to extract product attribute values into a specific format and it currently looks like:
I wish for it be like:
{
"Material":"Plastic",
"Printing Method":"Pad",
"Ink Colour":"Black",
"Barrel Colour":"Silver",
"Grip Colour":"Black"
}
I have attempted this:
$final_array = array();
foreach($product_decoded['product_attribute_values'] as $pav) {
$array = [
$pav['product_attribute_key']['name'] => $pav['name']
];
array_push($final_array, $array);
}
return json_encode($final_array);
This results in data looking like:
[
{"Material":"Plastic"},
{"Printing Method":"Pad"},
{"Ink Colour":"Black"},
{"Barrel Colour":"Silver"},
{"Grip Colour":"Black"}
]
How would this be achieved?
You can do it like this:
foreach($product_decoded['product_attribute_values'] as $pav) {
$array[$pav['product_attribute_key']['name']] = $pav['name'];
}
return json_encode($array);
For something like this you could use collections:
return collect($product_decoded['product_attribute_values'])
->pluck('name', 'product_attribute_key.name')
->toJson();
Alternatively, you could use the array helpers:
$finalArray = Arr::pluck($product_decoded['product_attribute_values'],'name', 'product_attribute_key.name' );
return json_encode($finalArray);
You need to have it in an object instead of an array.
$item = array("Material"=>"Plastic", "Printing Method"=>"Pad", "Ink Colour"=>"Black", "Barrel Colour"=>"Silver", "Grip Colour"=>"Black");
echo json_encode($item);
will result in this JSON:
[
{"Material":"Plastic"},
{"Printing Method":"Pad"},
{"Ink Colour":"Black"},
{"Barrel Colour":"Silver"},
{"Grip Colour":"Black"}
]
Which is correct JSON array syntax.
In order to get
{
"Material":"Plastic",
"Printing Method":"Pad",
"Ink Colour":"Black",
"Barrel Colour":"Silver",
"Grip Colour":"Black"
}
You would need soemthing like
$item->Material = "Plastic";
$item->PrintingMethod = "Pad";
$item->InkColour = "Black";
$item->Barrel Colour = "Silver";
$item->GripColour = "Black;
json_encode($item);
{
"books": [
{
"id": 2331,
"image": "http://lol.org/flower.png",
"images": [
{
"256x144": "http://lol.org/bee.png",
"650x320": "http://lol.org/fly.png"
}
],
....
I have json data like above but my problem is how to get out 650x320 data.
$data = json_decode($jsondata,true);
$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++){
Codes below works fine
$image = $data['books'][$x]['image'];
but how to fetch images on a second json level? I have tried code below with no luck.
$image = ($data->{'books'}->{'images'}->{'320x180'});
$image = $data['books']['images'][$x]['320x180'];
function getImageLinksFor($json, $dimension='650x320') {
$links = array();
$objJson = json_decode($json);
// GET THE MAIN BOOKS OBJECT...
$books = $objJson->books;
// LOOP THROUGH THE $books OBJECT AND PERFORM YOUR SEARCH FOR IMAGES
foreach ($books as $obj) {
// SINGLE OUT THE IMAGES OBJECT
$images = $obj->images;
// SINCE IT IS ALSO AN ARRAY, SIMPLY LOOP THROUGH IT AND FETCH THE DESIRED DIMENSION.
foreach ($images as $key => $objImgData) {
if(property_exists($objImgData, $dimension)){
$links[] = $objImgData->$dimension;
}
}
}
if(count($links) == 1){
return implode("", $links);
}
return $links;
}
var_dump(getImageLinksFor($json, '650x320'));
'books' is an Array of objects, you will need to select an object using a numeric index.
$image = $data['books'][$insertIndexHere]['images'][$insertIndexHere]['320x180'];
Essentially you have missed the [$x] between 'books' and 'images' from your first code which works.
You will probably want a loop which iterates through each book and then a second nested loop which iterates through the images in each book.
For example:
$gg = sizeof($data['books']);
for($x=0;$x<$gg;$x++) {
$images = data['books'][$x]['images'];
$sizeOfImages = sizeof($images);
for($j = 0; $j < $sizeOfImages; $j++) {
// access $images[$j]['320x180']
}
}
In PHP, how to get a JSON value from a variable path ?
Here is a sample json and a function with 2 params: a json variable, and path split into keys.
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
function getJSONValue($myjson, $pathkey) {
// split path keys by ";"
$myjson-> ?? $pathkey ??
}
echo getJSONValue($myjson, "myKey1;myKey2;myKey3;myKey4");
// Should display "myfinalvalue"
the static equivalent would be to do:
$myjson->myKey1->myKey2->myKey3->myKey4;
I tried:
$myjson->$pathkey
but unfortunately, it doesn't work...
Actually, your question has nothing to do with JSON. This is how you can get a value from a nested object:
function getValue($obj, $path) {
foreach(explode(';', $path) as $key) {
$obj = $obj->$key;
}
return $obj;
}
As for the JSON part, your example is not a valid JSON. It should be like this:
$myjson = json_decode('{
"myKey1": {
"myKey2": {
"myKey3": {
"myKey4": "myfinalvalue"
}
}
}
}');
Also, php objects are case-sensitive, if you have myKey in the object, it should be myKey (and not mykey) in the path string.
function getJSONValue($myjson, array $pathkey) {
foreach($pathkey as $val){
$myjson = $myjson->{$val};
}
return $myjson;
}
$myjson = json_decode('{"myKey1": {"myKey2": {"myKey3": {"myKey4": "myfinalvalue"}}}}');
echo getJSONValue($myjson, ["myKey1","myKey2","myKey3","myKey4"]);
live example: http://codepad.viper-7.com/1G78Fi
Something like this:
function getJSONValue() {
$args = func_get_args();
$json = array_shift($args);
$key = array_shift($args);
$value = $json->$key;
if(is_object($value)) {
array_unshift($args, $value);
return call_user_func_array('getJSONValue', $args);
}
return $value;
}
No error checking.
Seems like you are mixing PHP and JS. check this out to see how to create a Json string, then getting an onject out of it, and accessing keys:
$myjson = json_encode(array(
'myKey1' => array(
'mykey2' => array(
'mykey3' => array(
'myKey4' => "myfinalvalue"
)
)
)
));
$obj = json_decode($string);
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
or pasting the json directly:
$obj = json_decode(
'{
myKey1: {
mykey2: {
mykey3: {
myKey4: "myfinalvalue"
}
}
}
}');
echo $obj->myKey1->mykey2->mykey3->myKey4
// "myfinalvalue"
To understand it betterm, read about JSON_DECODE
I currently have an array that looks like this:
[[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]
I'm using:
preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($results));
to create an array that should look like this:
[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]
However I can't seem to get rid of the extra set of brackets.
My model:
function get_data()
{
$this->db->select('ItemName, QuantitySold');
$query = $this->db->get('transactions');
$results = array();
foreach ($query->result_array() as $row)
{
if(!isset($results[$row['ItemName']]))
$results[$row['ItemName']] = array('name' => $row['ItemName'], 'data' => array());
$results[$row['ItemName']]['data'][] = $row['QuantitySold'];
}
//Rekey arrays so they aren't associative
$results = array_values($results);
return $results;
}
My controller:
function test()
{
$this->load->model('data');
$series_data[] = $this->data->get_data();
$data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);
preg_replace('/"([^"]+)"\s*:\s*/', '$1:',json_encode($series_data));
$this->load->view('chart', $data);
}
thanks in advance.
Why use preg_replace.... this is simply json encoded data:
$string = '[[{"name":"Shirt","data":[1,1,5,5,1,10000]},{"name":"Skittles","data":[1,9,1,1]}]]';
var_dump(
json_encode(
json_decode($string)[0]
)
);