how to convert it in array while returnung in laravel - arrays

while creating an API I am having some issues while returning the data at response please help to resolve it
$user_role = [
'user_id' => $data,
'role_id' => 1,
];
my result
"user_role": {
"user_id": 191,
"role_id": 1
}
I want it in an array-like below
"user_role": [{
"user_id": 191,
"role_id": 1
}]

Try this
$user_role = [[
'user_id' => $data,
'role_id' => 1,
]];
return response()->json(["user_role" => $user_role], 200);

Related

How would I write a WordPress function to run a json_encode and file_put_contents whenever a specific CPT post is saved

I need to generate a custom JSON file from custom fields in a custom post type. But I'm not sure what the proper function is for accomplishing this, or if my syntax is anywhere close to correct in the first place. I haven't worked much with JSON, and have never attempted to create one from dynamic content before.
I'm using an example json file for the mapping plugin I'm using as my model, but I suspect that I'm not writing the array in the right format by using this other JSON file.
In any case, embarrassingly, here's what I've got so far (and it's definitely not working):
function wpdocs_retailers_json($post_id) {
$maplocations = Array( ?>
{
"mapwidth": "1000",
"mapheight": "500",
"categories": [ {
"id": "food",
"title": "Fast-foods & Restaurants",
"color": "#a5a5a2",
"show": "false"
},
{
"id": "dep",
"title": "Department Stores",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "clothing",
"title": "Clothing & Accessories",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "health",
"title": "Health & Cosmetics",
"color": "#a5a5a2",
"show": "true"
},
{
"id": "misc",
"title": "Miscellaneous",
"color": "#a5a5a2",
"show": "true"
} ],
<?php if(have_rows('mall_levels', 'option')) { ?>
"levels": [ {
<?php while(have_rows('mall_levels', 'option')) {
the_row();
$level_svg = get_sub_field('svg_mall_level');
$level = get_sub_field('what_level_is_this');
?>
"id": "<?php echo esc_html($level->slug); ?>",
"title": "<?php echo esc_html($level->name); ?>",
"map": "<?php echo $level_svg; ?>",
<?php $locargs = array(
'post_type' => 'retailers',
'post_status' => 'publish',
'posts_per_page' => 0,
'orderby' => 'title',
'order' => 'ASC'
);
$locloop = new WP_Query($locargs);
if($locloop->have_posts()) { ?>
"locations": [
<?php while($locloop->have_posts()) {
$locloop->the_post();
$space = get_field('space_id'); ?>
{
"id": "space-<?php echo $space; ?>",
"title": "<?php the_title(); ?>",
"about": "Lorem ipsum",
"description": "<?php the_content(); ?>",
<?php $cats = get_the_terms($post->ID, 'dir_cats');
$catsCount = count($cats);
if($catsCount = 0) { ?>
"category": "<?php echo $cat->name; ?>"
<?php }
if($catsCount > 0) { ?>
"category": [<?php echo '"' . __($cat->name) . '"'; ?>]
<?php } ?>
"link": "<?php the_permalink(); ?>",
"x": "0.3721",
"y": "0.4296"
},
<?php } //endwhile; ?>
]
<?php } //endif;
} //endwhile; ?>
},
]
<?php } //endif; ?>
}
<?php );
$json = json_encode($maplocations);
$bytes = file_put_contents('mall.json', $json);
}
add_action('save_post_retailers', 'wpdocs_retailers_json');
I think, at least in part, the array needs to be written more like this? But I'm not sure:
"mapwidth" => "1000",
"mapheight" =>"500",
"categories" => Array(
array(
"id" => "food",
"title" => "Fast-foods & Restaurants",
"color" => "#a5a5a2",
"show" =>"false"
),
array(
"id" => "dep",
"title" => "Department Stores",
"color" => "#a5a5a2",
"show" => "true"
),
...etc.
Thanks in advance for any guidance you can provide. I apologize for my utter lack of knowledge to begin with on this one. Please be kind.
(...) the array needs to be written more like this?
Yes, you want to use that array syntax to make your life easier in the long run (IMO at least).
Here are some changes to your code. Untested though so let me know how it goes and/or if you have any further comments/questions.
function wpdocs_retailers_json($post_id) {
$maplocations = array(
"mapwidth" => 1000,
"mapheight" => 500,
"categories" => array(
array(
"id" => "food",
"title" => "Fast-foods & Restaurants",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "dep",
"title" => "Department Stores",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "clothing",
"title" => "Clothing & Accessories",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "health",
"title" => "Health & Cosmetics",
"color" => "#a5a5a2",
"show" => "false"
),
array(
"id" => "misc",
"title" => "Miscellaneous",
"color" => "#a5a5a2",
"show" => "false"
)
)
);
// We have map levels, save them to
// our json file
if(have_rows('mall_levels', 'option')) {
$maplocations['levels'] = array();
while(have_rows('mall_levels', 'option')) {
the_row();
$level_svg = get_sub_field('svg_mall_level');
$level = get_sub_field('what_level_is_this');
$level_data = array(
"id" => esc_html($level->slug),
"title" => esc_html($level->name),
"map" => $level_svg,
)
$locargs = array(
'post_type' => 'retailers',
'post_status' => 'publish',
'posts_per_page' => 0,
'orderby' => 'title',
'order' => 'ASC'
);
$locloop = new WP_Query($locargs);
// We have some locations, save them as well
if($locloop->have_posts()) {
$level_data['locations'] = array();
while($locloop->have_posts()) {
$locloop->the_post();
$space = get_field('space_id');
$title = get_the_title();
$content = get_the_content();
$cats = get_the_terms(get_the_ID(), 'dir_cats');
$permalink = get_permalink();
$level_data['locations']['id'] = 'space-' . esc_attr($space);
$level_data['locations']['title'] = esc_html($title);
$level_data['locations']['about'] = 'Lorem Ipsum';
$level_data['locations']['description'] = $content;
if ( count($cats) ) {
$level_data['category'] = join(', ', wp_list_pluck($cats, 'name'));
}
$level_data['locations']['link'] = esc_url( $permalink );
$level_data['locations']['x'] = '0.3721';
$level_data['locations']['y'] = '0.4296';
}
// Restore original post data
wp_reset_postdata();
}
// Add our $level_data array to $maplocations
$maplocations['levels'][] = $level_data;
}
}
// Convert PHP array into JSON string
$json = json_encode($maplocations);
// Save json string to mall.json
$bytes = file_put_contents('mall.json', $json);
}
add_action('save_post_retailers', 'wpdocs_retailers_json');
Note that file_put_contents('mall.json', $json); probably should use a full path to the folder where you want to store your mall.json file.
#cabrerahector Got me super close. After a little more trial and error, the last part of the above needs to go like this:
$mapjson = json_encode($maplocations);
$j_dir = get_stylesheet_directory();
$mapdata = '/json/mall.json';
file_put_contents($j_dir . $mapdata, $mapjson, LOCK_EX);
update_post_meta($post_id, 'mall, $date);
}
add_action('save_post_retailers', 'retailers_map_json', 20);
(note, I did change the name of the function to "retailers_map_json" instead of "wpdocs_retailers_json".

convert array to array of object Laravel

my api receive single array of object from client side like following:
[
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4010",
"isRefund": 0,
"amount" : 1025
},
]
and whem try to validate request at api side checked success and process to database success my issue happen when try to sent multi object inside array like following :
[
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4010",
"isRefund": 0,
"amount" : 1025
},
{
"datetime": "2022-07-19 12:04:03",
"receiptNumber" : "4009",
"isRefund": 0,
"amount" : 1025
}
]
when i am try to validate first object inside array using foreach like following :
$array = $request->all();
foreach($array as $sdsa){
$this->validate($sdsa, [
'datetime' => 'required|date_format:Y-m-d H:i:s',
'amount' => 'required|numeric',
'isRefund' => 'required|integer|between:0,1',
'receiptNumber' => 'required|string',
]);
}
in this case api return error :
"message": "Argument 1 passed to App\\Http\\Controllers\\Controller::validate() must be an instance of Illuminate\\Http\\Request, array given,
so that i am asking how can convert this format:
array:4 [
"datetime" => "2022-07-19 12:04:03"
"receiptNumber" => "4010"
"isRefund" => 0
"amount" => 1025
]
to
{
array:4 [
"datetime" => "2022-07-19 12:04:03"
"receiptNumber" => "4010"
"isRefund" => 0
"amount" => 1025
]
}
You can use 'json_encode()'.
Example;
$myArray = array("datetime" => "2022-07-19 12:04:03", "receiptNumber" => "4010", "isRefund" => 0, "amount" => 1025);
Output;
[
"datetime" => "2022-07-19 12:04:03",
"receiptNumber" => "4010",
"isRefund" => 0,
"amount" => 1025,
]
Than if you use json_encode like this;
$myArray = json_encode($myArray);
Output;
{
[
"datetime" => "2022-07-19 12:04:03",
"receiptNumber" => "4010",
"isRefund" => 0,
"amount" => 1025,
]
}
You need to use
Validator::make($sdsa, [
'datetime' => 'required|date_format:Y-m-d H:i:s',
'amount' => 'required|numeric',
'isRefund' => 'required|integer|between:0,1',
'receiptNumber' => 'required|string',
])->validate()

Cakephp how can I fetch same table association data

I have a database table called miles, miles data looks like after fetch and return in Json.
"userMiles": [
{
"id": 278,
"gain_miles": 0.02,
"start_time": "2022-07-06T15:40:47+09:00",
"end_time": "2022-07-06T15:45:08+09:00",
},
{
"id": 279,
"gain_miles": 0.02,
"start_time": "2022-08-06T15:40:47+09:00",
"end_time": "2022-08-06T15:45:08+09:00",
},
]
I have written code to fetch data looks
$milesTable = TableRegistry::getTableLocator()->get( 'Miles' );
$query = $milesTable->find('all'));
try{
$userMiles = $this->paginate($query);
}
catch (NotFoundException $e){
$userMiles = [];
}
Now I'm trying to change this Json structure like below
"userMiles": [
{
"start_date": "06-July",
"miles":[
{
"id": 278,
"gain_miles": 0.02,
"start_time": "2022-07-06T15:40:47+09:00",
"end_time": "2022-07-06T15:45:08+09:00",
},
...
]
},
{
"start_date": "01-Mar",
"miles":[
{
"id": 281,
"gain_miles": 0.20,
"start_time": "2022-03-01T15:40:47+09:00",
"end_time": "2022-03-01T15:45:08+09:00",
},
...
]
},
]
For change Json Structure like above I have tried below codes , but don't know what is the procedure I will follow to get this output.
$query = $milesTable->find();
->select(["start_date" => "TO_CHAR(start_time,'DD-Mon')"])
->contain('Miles')
;
In `milesTable.php`
$this->hasMany('Miles',[
'foreignKey' => 'start_time',
'joinType' => 'LEFT',
]);
For this query getting error " "Unable to load Miles association. Ensure foreign key in Miles is selected."
My first query is Am I in right track ? Which procedure I can follow to get my desire output Json ?
I have tried by group by and order
$query = $milesTable
->find()
->select([
"start_date" => "TO_CHAR(start_time,'DD-Mon')",
"gain_miles",
"start_time",
"end_time",
])
->group(['start_date','id'])
->order(['start_time' => 'DESC'])
;
Output That I'm getting
"query": [
{
"start_date": "05-Jul",
"gain_miles": 400,
"start_time": "2022-07-05T14:14:23+06:00",
"end_time": "2022-07-06T14:14:23+06:00",
},
....
];
No if I use Collection
$collection = new Collection($query);
$miles = $collection->groupBy('start_date');
I'm getting my desire result, but problem is pagination, can I use pagination on collection $query data ? Or how can I implement pagination here ?
First you can select your group by start_date, then you can write a method in your Miles Entity. (Solution for postgresql)
$query = $this->paginate($milesTable
->find()
->select([
"start_date" => "TO_CHAR(start_time,'DD-Mon')",
])
->group(['start_date'])
);
then in your entity
public function _getMilesByStartTime()
{
return \Cake\ORM\TableRegistry::getTableLocator()->get('Miles')
->find()
->where([
"TO_CHAR(start_time,'DD-Mon') = '$this->start_date'"
]);
}
Now In controller
foreach ($query as $entity) {
$userMiles[] = [
'start_time' => $entity->start_date,
'miles' => $entity->milesByStartTime
];
}
$userMiles array should contain your data ! Have n't test but think it will help !

Build a custom array in Laravel

I am looping the database to get a list of countries with continents.
array: [
0 => array: [
"country" => "BE"
"continent" => "EU"
1 => array: [
"country" => "BG"
"continent" => "EU"
]
...
]
From that result, I want to create an array that shows all the continents with the countries inside.
array:[
0 => array: [
"continent" => "EU"
"countries" => [
"country" => "BE"
"country" => "BG"
]
]
Suppose this is your array
$arr = [
[
"country" => "BE",
"continent" => "EU",
],
[
"country" => "BG",
"continent" => "EU",
]
];
Then this returns what you expected.
collect($arr)->groupBy('continent')->mapWithKeys(function ($group, $continent) {
return [
'continent' => $continent,
'countries' => $group->pluck('country')->toArray()
];
});
If you need just to group countries by continent, simple way to achieve this by mapToGroups() method for collections
$input = [
['country' => 'BE', 'continent' => 'EU'],
['country' => 'BG', 'continent' => 'EU'],
['country' => 'BU', 'continent' => 'AF'],
['country' => 'BY', 'continent' => 'EU'],
];
$grouped = collect($input)
->mapToGroups(fn ($country) => [$country['continent'] => $country['country']])
->toArray(); // if you need array at the end
This will be resulted in
You will need to some how group your results by the continent. One way to do that is to loop over the initial collection and build a new array keyed by the continent.
However, seeing that you are using Laravel just group the collection by the continent.
$countries = [
['country' => 'A', 'continent' => 'aa'],
['country' => 'B', 'continent' => 'bb'],
['country' => 'C', 'continent' => 'aa'],
['country' => 'D', 'continent' => 'aa'],
['country' => 'E', 'continent' => 'aa'],
['country' => 'F', 'continent' => 'bb'],
];
// Because my data is an array I just turn that into a collection.
// But an Eloquent query builder ->get would already return a collection.
$continents = collect($countries)->groupBy('continent');
foreach ($continents as $continent => $items) {
echo "Countries for " . $continent . "\n";
foreach ($items as $country) {
echo $country['country'] . "\n";
}
}
/**
Output:
Countries for aa
A
C
D
E
Countries for bb
B
F
**/

Issue creating JSON feed in Laravel

I am trying to create a JSON feed using two arrays of data in the format mentioned below.
{
"items":[
{
"category_id":1,
"category_name":"Mens Clothing",
"child":[
{
"product_id":1,
"product_name":"Shirts"
},
{
"product_id":2,
"product_name":"T-Shirts"
}
]
}
]
}
However, I am getting like the following.
{
"items":[
{
"category_id":1,
"category_name":"Mens Clothing",
"child":[
]
}
],
"child":[
{
"product_id":1,
"product_name":"Shirts"
},
{
"product_id":2,
"product_name":"T-Shirts"
}
]
}
I have written the following in Laravel.
$data = [
'items' => [],
];
foreach ($categories as $key => $category) {
$data['items'][$key] = [
'category_id' => $category->id,
'category_name' => $category->category_name,
'child' => [],
];
}
foreach ($products as $key => $product) {
$data['child'][$key] = [
'product_id' => $product->id,
'product_name' => $product->product_name
];
}
Can anyone please help me figure out this issue?
If product has 'category_id' - something like the following can work:
$data = [
'items' => [],
];
foreach ($categories as $key => $category) {
$children = [];
foreach ($products as $key => $product){
if($product->category_id == $category->id) {
$children[] = $product;
}
}
$data['items'][$key] = [
'category_id' => $category->id,
'category_name'=> $category->category_name,
'child' => $children,
];
}

Resources