Json array of objects in php - php

this is the json that my code produces
{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555}
}
and this is the code
<?php
$c = array('a' => 11111, 'b' => 222222, 'c' => 33333, 'd' => 444454, 'e' => 55555555 );
$arr = array('aaa' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 , 'fff'=>$c);
echo json_encode($arr);
?>
but I want to have some structure like this
{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
"last":[
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}
I am new in json and php and I need this fast so I do not have time to read about this json structure... So please if someone know how to add this last element please provide some php code.
Thanks,

Take the "json-encoded" string and pass it to json_decode()
assign the return value to a variable
pass that variable to var_export() to get a "php-encoded" string representation of the data.
e.g.
<?php
$json = '{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
"last":[
{
"id": 8817,
"loc": "NEW YORK CITY"
},
{
"id": 2873,
"loc": "UNITED STATES"
},
{
"id": 1501,
"loc": "NEW YORK STATE"
}
]
}';
$php = json_decode($json, true);
echo var_export($php);
prints
array (
'aaa' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'fff' =>
array (
'a' => 11111,
'b' => 222222,
'c' => 33333,
'd' => 444454,
'e' => 55555555,
),
'last' =>
array (
0 =>
array (
'id' => 8817,
'loc' => 'NEW YORK CITY',
),
1 =>
array (
'id' => 2873,
'loc' => 'UNITED STATES',
),
2 =>
array (
'id' => 1501,
'loc' => 'NEW YORK STATE',
),
),
)

Related

Json starting with [ and when using json_encode it starts with " in magento2 using php7.1

I want my json to start with { but if using json_encode it is getting converted into string, I am using php7.1 on ubuntu and working on magento 2.3
This is what I am getting with the below code, I don't want '['
[
{
"success": "true",
"data": {
"mainimages": [
{
Here is my code
$response = array(
array(
"success" => "true",
"data" => $alldata,
"newarrivalheading" => "NEW ARRIVALS",
"instagramheading" => "CELEBS IN LULU",
"specialpriceheading" => "SPECIAL PRICES",
"editorwishlistheading" => "EDITOR'S WISHLIST",
"stylehighlightheading" => "STYLE HIGHLIGHTS",
"styletagline" => "#Looks to swipe right",
"newarrivalindex" => 3,
"instagramindex" => 9,
"editorwishlistviewall" => "",
"sliderimage" => $sliderimage
)
);
return $response;
This is what I want
{
"success": "true",
"data": {
"mainimages": [
{
So remove the unnecessary outer array like so
$alldata = [1,2,3,4];
$sliderimage = ['xz.jpg','ab.png'];
$response = array(
"success" => "true",
"data" => $alldata,
"newarrivalheading" => "NEW ARRIVALS",
"instagramheading" => "CELEBS IN LULU",
"specialpriceheading" => "SPECIAL PRICES",
"editorwishlistheading" => "EDITOR'S WISHLIST",
"stylehighlightheading" => "STYLE HIGHLIGHTS",
"styletagline" => "#Looks to swipe right",
"newarrivalindex" => 3,
"instagramindex" => 9,
"editorwishlistviewall" => "",
"sliderimage" => $sliderimage
);
echo json_encode($response);
RESULT
{
"success": "true",
"data": [
1,
2,
3,
4
],
"newarrivalheading": "NEW ARRIVALS",
"instagramheading": "CELEBS IN LULU",
"specialpriceheading": "SPECIAL PRICES",
"editorwishlistheading": "EDITOR'S WISHLIST",
"stylehighlightheading": "STYLE HIGHLIGHTS",
"styletagline": "#Looks to swipe right",
"newarrivalindex": 3,
"instagramindex": 9,
"editorwishlistviewall": "",
"sliderimage": [
"xz.jpg",
"ab.png"
]
}

How can I search an array for specific values?

I need some help with how I can search an array from a search box.
Lets say I search for the $ticker and write BTC
It will then print out:
The last known currency for BTC is 57
I only want it to print out $k3 values.
Appreciate if you could take your time and guide me in the right direction :)
<form method="POST" action="">
<input type="text" name="Searcharray" name="searcharray">
<input type="submit" value="Search" name="searcharray">
</form>
<?php
$ticker = array(
0 => "BTC",
1 => "ETH",
2 => "LTC",
3 => "XMR",
4 => "XRP"
);
$name = array(
0 => "Bitcoin",
1 => "Ethereum",
2 => "Litecoin",
3 => "Monero",
4 => "Ripple"
);
$k1 = array(
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5
);
$k2 = array(
0 => 11,
1 => 12,
2 => 13,
3 => 14,
4 => 15
);
$k3 = array(
0 => 17,
1 => 27,
2 => 37,
3 => 47,
4 => 57
);
?>
array_search would help - http://php.net/manual/de/function.array-search.php
$index = array_search('BTC', $ticker);
$value = $k3[$index];
Why dont you make such a structure?:
$data = [
'BTC' => [
'name' => 'Bitcoin',
'k1' => 1,
'k2' => 11,
'k3' => 17
], ...
];
then it would be:
$value = $data['BTC']['k3'];
$index = array_search("BTC", $ticker);
if ($index !== FALSE) {
$currency = $k3[$index];
echo "The last known currency of BTC is $currency";
}
But things would be easier if you used a 2-dimensional associative array:
$data = [
"BTC" => ["name" => "Bitcoin", "k1" => 1, "k2" => 11, "k3" => 17],
"ETH" => ["name" => "Ethereum", "k1" => 2, "k2" => 12, "k3" => 27],
...
];
Then you can do:
if (isset($data["BTC"])) {
$currency = $data["BTC"]["k3"];
echo "The last known currency of BTC is $currency";
}

Create an array of object PHP

I am trying to create this structure on PHP
and I don't know how to I create an array of object on PHP. It always get the last data from the object.
This is my current code:
array(
"description": getDescription($id),
"deposit": getPrices($id);
)
function getPrices($id) {
$test = Prices::where('price_id',$id)->where('promo',0)->get();
$price = [];
$data = [];
foreach($test as $t) {
$data["item_id"] = $t->id;
$data["price"] = $t->list;
$data["type"] = $t->type;
$price = $data;
}
return $price;
}
Fixing the actual issue with not receiving all records from the getPrices function:
array(
"description": getDescription($id),
"deposit": getPrices($id);
)
function getPrices($id) {
$test = Prices::where('price_id',$id)->where('promo',0)->get();
$price = [];
foreach($test as $t) {
$price[] = ["item_id" => $t->id, "price" => $t->list, "type": $t->type];
}
return $price;
}
You're missing the square brackets after $price (Correct: $price[]) variable which tells PHP to append to array rather than actually replace it.
The other option is to use array_push, which is more explicit but does the same; Read more here.
Fixing the issue of serialisation:
You can use json_encode to serialise the array into JSON (JavaScript Object Notation).
$dataArray=array();
foreach($test as $t) {
$dataArray[] = array('item'=> $t->id,'item'=> $t->price,'type'=> $t->type);
}
$finalArray= array('deposit'=>$dataArray);
convert final array to json using json_encode
$structure = new stdClass();
$structure->description = 'tobedefined'; // Define the description here
$structure->deposit = getPrices($id);
function getPrices($id) {
$deposits = array();
// Change this to contain the real data
// $test = Prices::where('price_id',$id)->where('promo',0)->get();
$test = array(
array(
'item_id' => 100,
'price' => '1, 2, 3, 4, 5',
'type' => 'child'
),
array(
'item_id' => 101,
'price' => '2, 4, 6, 8, 10',
'type' => 'child'
),
array(
'item_id' => 102,
'price' => '2, 4, 6, 8, 10',
'type' => 'child'
)
);
foreach ($test as $t) {
$deposit = new stdClass();
$deposit->item_id = $t['item_id'];
$deposit->price = $t['price'];
$deposit->type = $t['type'];
$deposits[] = $deposit;
}
return $deposits;
}
echo 'PHP Structure';
echo '<pre>';
print_r($structure);
echo '</pre>';
echo 'JSON string';
echo '<pre>';
print_r(json_encode($structure, JSON_PRETTY_PRINT));
echo '</pre>';
Output will be:
PHP Structure
stdClass Object
(
[description] => tobedefined
[deposit] => Array
(
[0] => stdClass Object
(
[item_id] => 100
[price] => 1, 2, 3, 4, 5
[type] => child
)
[1] => stdClass Object
(
[item_id] => 101
[price] => 2, 4, 6, 8, 10
[type] => child
)
[2] => stdClass Object
(
[item_id] => 102
[price] => 2, 4, 6, 8, 10
[type] => child
)
)
)
JSON string
{
"description": "tobedefined",
"deposit": [
{
"item_id": 100,
"price": "1, 2, 3, 4, 5",
"type": "child"
},
{
"item_id": 101,
"price": "2, 4, 6, 8, 10",
"type": "child"
},
{
"item_id": 102,
"price": "2, 4, 6, 8, 10",
"type": "child"
}
]
}

PHP Add null to array value if it doesn't exist

I'm generating data arrays and want to add 0/null to a specific month, where no data is present, but been struggling with it for few days.
I'm generating the final dataset array like this
foreach ($patients as $key => $item) {
$labels[] = $item['month'];
usort($labels, "compare_months");
$labels = array_unique($labels);
$chartData[ $item['brand_name'] ]['data'][] =
$item['patientsCount'];
$chartData[ $item['brand_name'] ]['brand_data'] = [
"name" => $item['brand_name'],
"color" => $item['color']
];
}
foreach ($chartData as $item) {
$pointRadius++;
$dataSet[] = [
'label' => $item['brand_data']['name'],
'data' => $item['data'],
'pointRadius' => $pointRadius,
'fill' => false,
'borderWidth' => 1,
'backgroundColor' => "#" . $item['brand_data']['color'],
'borderColor' => "#" . $item['brand_data']['color'],
];
}
$finalData[] = [
'labels' => $labels,
'datasets' => $dataSet
];
Which gives me this json response
[
{
"labels":[
"April",
"May",
"June",
"July"
],
"datasets":[
{
"label":"Medicine 1",
"data":[
1
],
"pointRadius":1,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ea5f2d",
"borderColor":"#ea5f2d"
},
{
"label":"Medicine 2",
"data":[
1,
1,
1
],
"pointRadius":2,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ffb400",
"borderColor":"#ffb400"
},
{
"label":"Medicine 3",
"data":[
1,
1,
2
],
"pointRadius":3,
"fill":false,
"borderWidth":1,
"backgroundColor":"#ff7777",
"borderColor":"#ff7777"
},
{
"label":"Medicine 4",
"data":[
1,
1,
2
],
"pointRadius":4,
"fill":false,
"borderWidth":1,
"backgroundColor":"#64a36f",
"borderColor":"#64a36f"
},
{
"label":"Medicine 5",
"data":[
2
],
"pointRadius":5,
"fill":false,
"borderWidth":1,
"backgroundColor":"#e7e6fc",
"borderColor":"#e7e6fc"
}
]
}
]
As you can see, for some items, the data object only contains 1 value which is wrong, because I need to add zeros to months, where there is no data.
Can this be done in MySQL or is it better to use PHP and how?
EDIT 1
Here is the array I am currently getting.
Array
(
[MEDICINE 1] => Array
(
[April] => 1
)
[MEDICINE 2] => Array
(
[April] => 1
[July] => 2
)
[MEDICINE 3] => Array
(
[April] => 1
[May] => 1
[July] => 2
)
[MEDICINE 4] => Array
(
[May] => 1
[July] => 3
)
[MEDICINE 5] => Array
(
[June] => 2
)
[MEDICINE 6] => Array
(
[July] => 1
)
)
As you can see some medicines have data for only one month and I want to add these months to the medicine array with 0 value, if there is no data.
Add this line after each foreach: if (count($item['data']) < 2) continue;. Because you need skip if length of data is smaller than 2.
foreach ($patients as $key => $item) {
if (count($item['data']) < 2) continue;
$labels[] = $item['month'];
usort($labels, "compare_months");
$labels = array_unique($labels);
$chartData[ $item['brand_name'] ]['data'][] =
$item['patientsCount'];
$chartData[ $item['brand_name'] ]['brand_data'] = [
"name" => $item['brand_name'],
"color" => $item['color']
];
}
foreach ($chartData as $item) {
$pointRadius++;
if (count($item['data']) < 2) continue;
$dataSet[] = [
'label' => $item['brand_data']['name'],
'data' => $item['data'],
'pointRadius' => $pointRadius,
'fill' => false,
'borderWidth' => 1,
'backgroundColor' => "#" . $item['brand_data']['color'],
'borderColor' => "#" . $item['brand_data']['color'],
];
}
$finalData[] = [
'labels' => $labels,
'datasets' => $dataSet
];

Get specific key value pairs from associative array

I`m new to PHP and probably this one is basic question, but...I have an associative array (result of json_decode function). For example it looks like this:
$cars = array
(
array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
array("brand"=>"Audi", "price" => 20000, "type"=> 2),
array("brand"=>"Ford", "price" => 30000, "type"=> 3),
array("brand"=>"Audi", "price" => 31000, "type"=> 3),
array("brand"=>"Ford", "price" => 32000, "type"=> 2),
array("brand"=>"Audi", "price" => 33000, "type"=> 2)
);
I need to loop $cars and get just brand and price as key value pair where brand is Audi because of a need to convert each to an object then.
Thanks!
Pretty simple. Use foreach to iterate through each car. If car brand name is 'Audi' then it will add it the entry it's on to an array.
<?php
$cars = array
(
array("brand"=>"Volvo", "price" => 10000, "type"=> 1),
array("brand"=>"Audi", "price" => 20000, "type"=> 2),
array("brand"=>"Ford", "price" => 30000, "type"=> 3),
array("brand"=>"Audi", "price" => 31000, "type"=> 3),
array("brand"=>"Ford", "price" => 32000, "type"=> 2),
array("brand"=>"Audi", "price" => 33000, "type"=> 2)
);
$audis = [];
foreach ($cars as $car) {
if ($car['brand'] == 'Audi') {
$audis[] = ['price' => $car['price'], 'type' => $car['type']];
}
}
foreach ($audis as $audi) {
print_r($audi);
}
This returns all Audi's
Array
(
[price] => 20000
[type] => 2
)
Array
(
[price] => 31000
[type] => 3
)
Array
(
[price] => 33000
[type] => 2
)
Link: https://eval.in/769607

Categories