I'm trying to construct a json object containing inner objects.
I'm trying the following code - where $ids is an array containing some IDs:
$result = array();
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
array_push($result, $tempArray);
}
print_r(json_encode($result));
The getCustomOptions() also returns an array using the following script:
$dataArray = [];
while ($stmt->fetch()) {
$dataArray[] = array(
'id' => $id,
'description' => $description
);
}
The problem is that when I print_r(json_encode($result)); I'm getting the following result:
[
[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
],
[
]
]
As you can see it returns some arrays inside of an array, but what I really need is the following structure:
{
"data1":[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
"data2":[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
]
}
I know that I'm missing something really small and basic here, but for me the JSON manipulation in php is still hard.
Can somebody give me a clue or a push?
you can try following code to generate your array in a proper format.
$result = array();
$i=1;
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
$result['data'.$i] = $tempArray;
$i++;
}
Don't use array_push() that just creates a normal array element. Use $array_variable[$key] = ... to assign values to a specific associative array key.
Related
I have been struggling with this for quite some time. I have two arrays, which I need to combine.
This is my input:
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
Now the structure is, that each item in each array follows each other. So, the result should be something like:
{
"result": [
{
"mrn" : "18DK00310020B11A84",
"shipper" : "1861575"
},
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
]
}
However I simply cannot figure out how to do this.
I have tried to merge the two original arrays:
//Input
$array_one = $request->array_one;
$array_two = $request->array_two;
//Merge the two received arrays
$final = array_merge_recursive($array_one, $array_two);
However, this just removes array_one and array_two, but the array is still split up.
How can I combine above array, so it will have below format:
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
You can do this with some custom code:
$array_one = $request->array_one;
$array_two = $request->array_two;
$final = array_map(function ($value, $key) use ($array_two) {
foreach ($value as $k => $v) {
return [
"mrn" => $v,
"shipper" => array_get($array_two, "shipperreference.$key.$k")
];
}
}, array_get($array_one, 'mrnreference'), array_keys(array_get($array_one, 'mrnreference')));
A very quick solution to this would be just to iterate through a for loop.
for($i = 0; $i < count($array_one); $i++){
$final[$i]["mrn"] = $array_one["mrnreference"][$i]; // Mrn key equals array one value
$final[$i]["shipping"] = $array_two["shipperreference"][$i]; // Shipping key equals array two value
}
However, this has a small caveat that it could lead to an error, if $array_one and $array_two are not the same size.
First of all array_map can be used to get the values and then in simple for loop you can combine them. Notice that the size of mrnreference and shipperreference must be the same otherwise it will pop notice
$json = '
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
';
$arr = json_decode($json, true);
$ref = array_map(function($e){return $e['key_0'];}, $arr['array_one']['mrnreference']);
$ship = array_map(function($e){return $e['key_0'];}, $arr['array_two']['shipperreference']);
$output = array();
for ($i = 0, $cnt = count($ref); $i < $cnt ; ++$i) {
$output[] = [
'mrn' => $ref[$i],
'shipper' => $ship[$i],
];
}
echo json_encode(['result' => $output]);
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
I have an Array containing sub-sets of data as following:
"options":[
{
"id":"13",
"option_name":"M",
"option_id":"1",
"label":"Size"
},
{
"id":"13",
"option_name":"L",
"option_id":"1",
"label":"Size"
},
{
"id":"13",
"option_name":"BLUE",
"option_id":"1",
"label":"Color"
},
{
"id":"13",
"option_name":"GREEN",
"option_id":"1",
"label":"Color"
}
]
I want to loop into this array and separate objects/subsets based on key label. As following:
"options":[
{
"label":"Size",
"optionsArray":[
{
"id":"11",
"option_name":"XL",
"option_id":"1",
"label":"Size",
},
{
"id":"12",
"option_name":"L",
"option_id":"1",
"label":"Size",
}
]
},
{
"label":"Color",
"optionsArray":[
{
"id":"11",
"option_name":"BLUE",
"option_id":"1",
"label":"Color",
},
{
"id":"12",
"option_name":"GREEN",
"option_id":"1",
"label":"Color",
}
]
}
]
How can i achieve this with PHP?
As this post is already full of code, stackoverflow wouldn't let me paste my current try of code, so i will try to paste simple structure as plain text.
$keys = array_keys(current($options));
$len = count($options);
foreach($keys as $key){
// Access the key first
for($i=0;$i<$len; $i++){
// access the row later
echo $array[$i][$key];
}
}
I'd do it like that:
$result = [];
foreach ($options as $option) {
if (!isset($result[$option['label']])) {
$result[$option['label']] = [
'label' => $option['label'],
'optionsArray' => []
];
}
$result[$option['label']]['optionsArray'][] = $option;
}
$result = array_values($result);
<?php
// Decode the JSON (true for using associative arrays)
$array = json_decode($json, true);
// Initialize three arrays
$colors = [];
$sizes = [];
$unknown = [];
// Loop and seperate them using a switch
foreach ($array['options'] as $o) {
if (! isset($o['label'])) {
trigger_error('label not in object', E_USER_WARNING);
}
switch($o['label']) {
case 'Size':
$sizes[] = $o;
break;
case 'Color':
$colors[] = $o;
break;
// Put all malformed objects into this array
default:
$unknown[] = $o;
}
}
// You can now easily build your new array
$output = ['options' => [
['label' => 'Size', 'optionsArray' => $sizes],
['label' => 'Color', 'optionsArray' => $colors]
]];
I am trying to get access to some data in PHP. If I print my docuements as a JSON object I get the document like so:
print_r($url);
[
{
"channel": "hello.com",
"partone": {
"click": 30580,
"load": 2156552
},
"parttwo": {
"click": 3274,
"load": 402327
},
"partthree": {
"click": 406467,
"load": 903869
}
}
]
So my main idea is to get the "click" of "parttwo" but I am getting null. This is my PHP code where I am making the mistake:
foreach ($url[0]['parttwo'] as $obj) {
$doc = array();
$doc['click'] = $obj['click'];
$param []= $doc;
}
Fo that data, simply:
$array = json_decode($url, true);
$param = $array[0]['part2']['click'];
If you really need to loop then:
foreach($array as $value) {
$param[] = $value['part2']['click'];
}
I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.
Json file
{
"app":{
"available":{
"stats":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
],
"stats2":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
]
}
}
}
I use
foreach($data3['app']['available'] as $name => $value)
{
foreach($value as $entry)
{
echo $entry['name'];
}
}
The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?
because there are two arrays in app->available: stats and stats2
If you are interested in only stats, why don't you try:
foreach($data3['app']['available']['stats'] as $name => $value)
__UPDATE__
Try this one please
$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';
$obj = (array) json_decode($in, true);
foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
{
echo ($value['name'] );
echo ("\r");
}
}