PHP Associative Array to JSON - php

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

Related

How to remove the arrays given in the arrows

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

How to convert sql query result in Json Object {"timestamp": value}

i want to use Cal-Heatmap to visualize data and my current sql result is returned as
[ { "dateStampSecs": "1499637600", "value": "1" } ]
but i want
[ { "1499637600" : 1 } ]
How do I stick them together?
I am using Codeigniter and below is my sql:
public function get_calData(){
$this->db->select('unix_timestamp(STR_TO_DATE(date_start, "%Y-%m-%d")) dateStampSecs,count(*) as value');
$this->db->from('calendar');
$query = $this->db->get()->result();
print json_encode($query,JSON_PRETTY_PRINT);
}
$dateStampSecs = array_column($query, "dateStampSecs");
$value = array_column($query, "value");
$result = array_combine($dateStampSecs, $value);
print json_encode($result,JSON_PRETTY_PRINT);
you have to echo the result like following
echo json_encode($query);
exit();
Try like this
$finalData='';
foreach ($query as $data){
$finalData[][$data['dateStampSecs']]=$data['value'];
}
$finalData=json_encode($finalData);
dd($query,$finalData);
It will give output as
Hope it will work
$query = json_decode($query ,true);
$query = [$query['dateStampSecs']=>$query['value']];
dd(json_encode($query));`

Creating new JSON by reading distinct JSON array elements in PHP

I have a JSON object that looks something like this
OBJECT $deals
[
{
"deal_id": 124563
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 456789
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 46646
"merchant_id": 456
"merchant_name": Merchant2
}
]
What I am trying to do is this right now
$category_merchants = array();
foreach ($deals as $deal) {
array_push($category_merchants, $deal->merchant_id, $deal->merchant_name)
}
$category_merchants = json_encode($category_merchants);
The new JSON object has all the merchants from the original JSON. Is there an easy way to just get the distinct merchants (merchant_name, merchant_id) in the new JSON with counts of how many times they were in the original JSON?
use array_map() like this:
array_map(function($v){return [$v->merchant_id, $v->merchant_name];}, $array);
Convert json to array
$array = json_decode($deals);
loop array to get unique merchant name
foreach($array as $key => $value) {
$category_merchants[$value['merchant_id']] = $value['merchant_name'];
$category_merchant_count[] = $value['merchant_id']; //this is to count number of merchant occurance
}
Convert category_merchants back to json
$merchant = json_encode($category_merchants);
Get number of merchant occurance
print_r(array_count_values($category_merchant_count))
One way. Just use the merchant_id as the key and increment the count:
$deals = json_decode($json, true);
foreach ($deals as $deal) {
if(!isset($category_merchants[$deal['merchant_id']])) {
$category_merchants[$deal['merchant_id']] = $deal;
$category_merchants[$deal['merchant_id']]['count'] = 1;
unset($category_merchants[$deal['merchant_id']]['deal_id']);
} else {
$category_merchants[$deal['merchant_id']]['count']++;
}
}
If you need to re-index the array then:
$category_merchants = array_values($category_merchants);

PHP check variable if exists in array of json

Array : [{"ID":1},{"ID":2}]
$id=1;
I want to check if $id exists in the array.
Thank you!
You may try Laravel's Collection::contains method, for example:
$collection = collect(json_decode($jsonString, true));
if ($collection->contains(1) {
// Exists...
}
Also, you may use key/value pair like this:
if ($collection->contains('ID', 1) {
//...
}
Also, if you want to get that item from the collection then you may try where like this:
$id = $collection->where('ID', 1)->first(); // ['ID' => 1]
You have a json formatted array and you need to decode it using json_decode first. After that loop the array to check for the id that you want.
So the code should look like this:
$json = '[{"ID":1},{"ID":2}]';
$id = 1;
$data = json_decode($json, true);
foreach($data as $item){
if($item['id'] == $id) {
echo 'it exists';
}
}
Iterate the array using for loop and use the value as a param to json_decode.
$id = 1;
$arr = array('{"ID":1}', '{"ID":2}');
foreach($arr as $val) {
if (in_array($id, json_decode($val, TRUE))) {
echo "id present";
}
}
Try this, if value is exist it will give key of array
$jsondata = '[{"ID":1},{"ID":2}]';
$array = json_decode($jsondata,true);
$key = array_search(1, array_column($array, 'ID'));
Just check if the string is in the json array, with little computation.
I think it's the more efficient way. Check the result here.
<?php
$id = 1;
$array = ['{"ID":1}', '{"ID":2}'];
echo in_array(json_encode(["ID" => $id]), $array) ? 'Yes' : 'No';

preg_replace remove [] around array

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

Categories