Make separate php arrays from one json file - php

I have this json source file:
{
"results":
[
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
},
{
"movie_title":"A Monster Calls",
"cinema":"uptown"
},
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
},
{
"movie_title":"A Monster Calls",
"cinema":"downtown"
}
]
}
and I am writing my array like this (simplified for clarity):
$json_data = json_decode($html, true);
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
$moviesList[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}
But what I want to do is output 2 separate arrays. One is all films showing in "downtown" cinema, and the other array all films showing in "uptown". The order in the json file will change, so I have to do it by name.
What's the best way to do this?

$downtownArray = array();
$uptownArray = array();
$json_data = json_decode($html, true);
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
if ($cinema == 'uptown') {
$uptownArray[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
} else {
$downtownArray[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}
}

foreach ($json_data['results'] as $result) {
$cinema = $result['cinema'];
$moviesList[$cinema] []= [
"movieTitle" => $result['movie_title'],
// ...
];
}
The code classifies the results by the cinema field and stores them into $moviesList array. So, for example, the uptown results will be stored into $moviesList['uptown'].

You may try something like this
$json_data = json_decode($html, true);
$moviesDwn=array();
$moviesUp=array();
for($i = 0; $i < count($json_data['results']); $i++) {
$movieTitle = $json_data['results'][$i]["movie_title"];
$cinema = $json_data['results'][$i]["cinema"];
if ($json_data['results'][$i]["cinema"]='uptown')
$moviesUp[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
else if ($json_data['results'][$i]["cinema"]='updown')
$moviesDwn[]= array(
"movieTitle" => $movieTitle,
"cinema" => $cinema
);
}

First of all please , FIXyou JSON ,as it has some extra comma and then try with below codes
If you want to just separate the two array than use foreach(){};
foreach ($json_data['results'] as $result) {
$DownTown_List[$result['cinema']] []= $result['movie_title'];
}
OR
if you want to do other operation with the Indexes then use for(){};
for($i = 0; $i < count($json_data['results']); $i++) {
if($json_data['results'][$i]["cinema"] === "downtown"){
$DownTown_List["downtown"][] = $json_data['results'][$i]["movie_title"];
}
if($json_data['results'][$i]["cinema"] === "uptown"){
$DownTown_List["uptown"][] = $json_data['results'][$i]["movie_title"];
}
}
echo "<pre>";print_r($DownTown_List);exit;
OUTPUT
Array
(
[downtown] => Array
(
[0] => A Monster Calls
[1] => A Monster Calls
[2] => A Monster Calls
)
[uptown] => Array
(
[0] => A Monster Calls
)
)

Related

Creating a nested array dynamically with for loop

I have a loop that looks like this
$folder = [];
$explode = explode("/", $product->folder);
for($i = 0; $i < count($explode); $++)
{
$folder[$i] = 'test'
}
dd($folder);
what I'm trying to do here is to create a nested array depending on how many folders there are based on what I get from $explode.
So ideally what I want is this
[
"folder1" => [
"folder2" => "test"
]
]
and it would carry on being nested, so if my $product->folder looks like this cat1/cat2/cat3 then the array would looks like this
[
"cat1" => [
"cat2" => [
"cat3" => "product"
]
]
]
You can build nested array using JSON string and convert into array using json_decode
$path = 'cat1/cat2/cat3/cat4/product';
$folders = explode('/',trim($path,'/'));
$last = array_pop($folders);
$folders = str_replace(': []',': "'.$last.'"',
array_reduce(array_reverse($folders),function($carry,$item) {
if($carry) {
return '{"'.$item.'": '.$carry.'}';
}
return '{"'.$item.'": []}';
})
);
$folders = json_decode($folders,true);
// Test
print_r($folders);
and it will be result as :
Array
(
[cat1] => Array
(
[cat2] => Array
(
[cat3] => Array
(
[cat4] => product
)
)
)
)
and formatted result
[
"cat1" => [
"cat2" => [
"cat3" => [
"cat4" => "product"
]
]
]
]
Simple solution for your problem
$path = 'cat1/cat2/cat3/product';
$folder = [];
$explode = explode("/", $path);
for($i = 0; $i < count($explode)-1; $i++)
{
if($i+1 >= count($explode)-1)
$folder[$explode[$i]] = $explode[$i+1];
else
$folder[$explode[$i]] = '';
}
print_r($folder) result will be this
Array ( [cat1] => [cat2] => [cat3] => product )
Please try the following.
// Add product title first.
$folder = end($explode);
// Iterate over categories to create a nested array.
for ($counter = count($explode) - 2; $counter >= 0; $counter--) {
$folder = [$explode[$counter] => $folder];
}

How to get if data exist in array in php

I am making laravel project.
I need to get data list from request.
So should get this data if data exist next.
I used below code...
for($i = 0; $i < count($request->post('pickup_location')); $i++)
{
if($request->post('meeting_ids')[$i])
{
$meeting_profile = MeetingPoint::findOrFail($request->post('meeting_ids')[$i]);
$meeting_data = array(
'pickup_location' => $request->post('pickup_location')[$i],
'pickup_type' => $request->post('pickup_type')[$i],
'pickup_time' => $request->post('pickup_time')[$i],
);
$meeting_profile->fill($meeting_data);
$meeting_profile->save();
} else {
$meeting_profile = new MeetingPoint;
$meeting_data = array(
'holiday_id' => $profile->id,
'pickup_location' => $request->post('pickup_location')[$i],
'pickup_type' => $request->post('pickup_type')[$i],
'pickup_time' => $request->post('pickup_time')[$i],
);
$meeting_profile->fill($meeting_data);
$meeting_profile->save();
}
}
But there is this error:
How can I get next data list with that logic?
Please do like below...
for($i = 0; $i < count($request->post('pickup_location')); $i++)
{
if(isset($request->post('meeting_ids')[$i]))
{
$meeting_profile = MeetingPoint::findOrFail($request->post('meeting_ids')[$i]);
$meeting_data = array(
'pickup_location' => isset($request->post('pickup_location')[$i]) ? $request->post('pickup_location')[$i] : null,
'pickup_type' => isset($request->post('pickup_type')[$i]) ? $request->post('pickup_type')[$i] : null,
'pickup_time' => isset($request->post('pickup_time')[$i]) ? $request->post('pickup_time')[$i] : null,
);
$meeting_profile->fill($meeting_data);
$meeting_profile->save();
} else {
$meeting_profile = new MeetingPoint;
$meeting_data = array(
'holiday_id' => $profile->id,
'pickup_location' => isset($request->post('pickup_location')[$i]) ? $request->post('pickup_location')[$i] : null,
'pickup_type' => isset($request->post('pickup_type')[$i]) ? $request->post('pickup_type')[$i] : null,
'pickup_time' => isset($request->post('pickup_time')[$i]) ? $request->post('pickup_time')[$i] : null,
);
$meeting_profile->fill($meeting_data);
$meeting_profile->save();
}
}
You could use Arr Helper function to more clean and organized code.
$values = $request->all();
for($i = 0; $i < count(Arr::get($values, 'pickup_location')); $i++)
{
if($id = Arr::get($values, "meeting_ids.{$i}"))
{
$meeting_profile = MeetingPoint::findOrFail($id);
$meeting_data = array(
'pickup_location' => Arr::get($values, "pickup_location.{$i}"),
'pickup_type' => Arr::get($values, "pickup_type.{$i}"),
'pickup_time' => Arr::get($values, "pickup_time.{$i}"),
);
$meeting_profile->fill($meeting_data);
$meeting_profile->save();
} else {
...
}
}
Please do like below
<?php
$array1 = [
"Orange" => 100,
"Apple" => 200,
"Banana" => 300,
"Cherry" => 400
];
if ( array_key_exists("Banana", $array1) )
echo "Array Key exists...";
else
echo "Array Key does not exist...";
?>

Divide numbers in 2 multidimensional array

I have 2 sets of multidimensional array ($profit & $sales). I want to divide the numbers in 2 multidimensional array to get the % of margin (using this formula: $profit/$sales*100)
$profit= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"15"
)
);
$sales= array(
0 => array(
"no"=> "1",
"value"=>"100"
),
1=> array(
"no"=> "2",
"value"=>"200"
)
);
This is the expected output:
$margin= array(
0 => array(
"no"=> "1",
"value"=>"10"
),
1=> array(
"no"=> "2",
"value"=>"7.5"
)
);
I have done some search with no luck still, below is the function that I'm using, it is not working:
function ArrayDivide($arrayList = [])
{
$m = [];
$no_details = [];
$i = 0;
foreach ($arrayList as $arrayItem) {
foreach ($arrayItem as $subArray) {
if (isset($no_details[$subArray['x']])) {//if no is exist
$m[$no_details[$subArray['x']]]['y'] = $m[$no_details[$subArray['x']]]['y'] /$subArray['y']*100;
} else {
$no_details[$subArray['x']] = $i;
$m[$i] = ["x"=>$subArray['x'], "y"=>"0"];
$i++;
}
}
}
return $m;
}
How you done similar function before? Where should I fix?
Thanks.
Use "Sourcey86" code and replace:
$res = $value / $no;
to
$res = $value/$sales[$key]['value']*100;
(I don't have enough points to add a comment on his post :D )
Something like this ? If I understood your question correctly.
function getMargin($profit, $sales){
$margin = [];
foreach($profit as $key => $val){
$no = $val['no'];
$value = $val['value'];
if(isset($sales[$key]) && $sales[$key]['no'] == $no){
$res = ($value/$sales[$key]['value'])*100;
$margin[$key]['no'] = $no;
$margin[$key]['val'] = $res;
}
}
return $margin;
}
var_dump(getMargin($profit, $sales));

Merge duplicate values from array in Json Formate

I am fetching data from location MySql table as structure is below
in my PHP code
I need send Json output in response as below (Table data may not be same as below json data but the format is same)
http://jsoneditoronline.org/?id=7c5600712df6f9ec1f8fbb8a13aba3de
Tried to do the following in the code to convert the array that i fetch from the table but however am unable to get it in the right format
$sql = "SELECT * FROM mobile_user_regions";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$resCArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ress = array();
foreach ($resCArray as $key => $value) {
$ress['regions'][] = array(array(
'name' => $value['region'],
'location' => array(
array(
'name' => $value['location'],
'store' => array(
'store_details' => $value['store_details'],
'store_phone' => $value['store_phone'],
'store_email' => $value['store_email'],
'store_latitude' => $value['store_latitude'],
'store_longitude' => $value['store_longitude']
)
)
)
)
);
Output: that i am getting is
**http://jsoneditoronline.org/?id=4d4a75177350e254ceee7238af13f2f7**
$regionArray = $xyzObject->getRegion();
if (!empty($regionArray) && isset($regionArray)) {
$i = 0;
$locationData = array();
foreach ($regionArray as $key => $value) {
$locationData['regions'][$i]['name'] = $value['region'];
$locationArray = $xyzObject->getLocation($value['region']);
$locationData['regions'][$i]['locations'] = $locationArray;
$i++;
}
$j = 0;
foreach ($locationData['regions'] as $key => $regions) {
$k = 0;
foreach ($regions['locations'] as $key1 => $locations) {
$storeArray = $xyzObject->getStore($locations['name']);
$locationData['regions'][$j]['locations'][$k]['stores'] = $storeArray;
$k++;
}
$j++;
}
echo json_encode($locationData);

PHP: Building a hierarchistic array structure

I'm having some problems building an hierarchistic array structure - I have almost got it done, but there's something unexplained that makes my array look weird which I hoped you could help me with.
The tree structure is:
root
|data
|-children
|--data
|--children
|---data
|---children
Any child can have any number of children and each child can have any number of parents.
I have a function that builds the tree:
private function build_tree($rows,$parent) {
$i = 0;
$response -> result = array();
$result = array();
$leaf = false;
foreach($rows as $row) {
if($row['parent_id'] == $parent) {
$leaf = is_null($row['treeDef']) ? false : true;
$workingSet = array_merge($result,array(
'id' => (int)$i,
'parent_id' => (int)$row['parent_id'],
'child_id' => (int)$row['id'],
'name' => (string)$row['resourceName'],
'updated' => strtotime($row['updated']),
'purchasedUnit' => (string)$row['purchasingUnit'],
'purchasedCost' => (double)$row['purchasingCosts'],
'purchasedDiscount' => (double)$row['discount'],
'estimateUnit' => (string)$row['estimatingUnit'],
'profitAddOn' => (string)$row['profitAddOn'],
'landedCost' => (double)$row['landedCost'],
'unitCorrelation' => (double)$row['unitCorrelation'],
'leadTime' => (string)$row['leadTime'],
'ResourceClassShortname' => (string)$row['ResourceClassShortname'],
'supplierName' => (string)$row['nameSupplier'],
'iconCls' => (string)$row['typeIcon'],
'leaf' => $leaf
));
$hasChildren = $this->Resource_model->has_children($rows,$row['id']);
if ($hasChildren->check) {
if (!$leaf) {
for($j=0; $j <= ($hasChildren -> rows); $j++) {
$parentArray = $workingSet;
$childArray = $this -> Resource_model -> build_tree($rows,$row['id']);
$workingSet = array_merge($parentArray,array('children' => $childArray -> result));
}
}
}
$result[$i] = $workingSet;
$i++;
}
}
$response -> result = $result;
$response -> rows = $i;
return $response;
}
Which produces this JSON:
Big picture
Every item that has 2 children (or more? - no test values) gets the first item like it should be, but the second item contains the first item as well - duplicating all the results.
Any help appreciated.
Instead of array_merge use array_push - this will add the children subarray instead of trying merging it with the one already existing...
It's in this part of code (already edited):
$hasChildren = $this->Resource_model->has_children($rows,$row['id']);
if ($hasChildren->check) {
if (!$leaf) {
for($j=0; $j <= ($hasChildren->rows); $j++) {
$parentArray = $workingSet;
$childArray = $this->Resource_model->build_tree($rows,$row['id']);
$workingSet = array_push($parentArray,array('children' => $childArray->result));
}
}
}
Made it work, here's the final code:
private function build_tree($rows,$parent) {
$i = 0;
$response -> result = array();
$result = array();
$leaf = false;
$newArray = array();
foreach($rows as $row) {
if($row['parent_id'] == $parent) {
$leaf = is_null($row['treeDef']) ? false : true;
$newArray = array(
'id' => (int)$i,
'parent_id' => (int)$row['parent_id'],
'child_id' => (int)$row['id'],
'name' => (string)$row['resourceName'],
'updated' => strtotime($row['updated']),
'purchasedUnit' => (string)$row['purchasingUnit'],
'purchasedCost' => (double)$row['purchasingCosts'],
'purchasedDiscount' => (double)$row['discount'],
'estimateUnit' => (string)$row['estimatingUnit'],
'profitAddOn' => (string)$row['profitAddOn'],
'landedCost' => (double)$row['landedCost'],
'unitCorrelation' => (double)$row['unitCorrelation'],
'leadTime' => (string)$row['leadTime'],
'ResourceClassShortname' => (string)$row['ResourceClassShortname'],
'supplierName' => (string)$row['nameSupplier'],
'iconCls' => (string)$row['typeIcon'],
'leaf' => $leaf
);
$hasChildren = $this -> Resource_model -> has_children($rows,$row['id']);
if ($hasChildren->check) {
for($j=0; $j <= ($hasChildren -> rows); $j++) {
$childArray = $this -> Resource_model -> build_tree($rows,$row['id']);
$newArray = array_merge($newArray, array('children' => $childArray -> result));
}
}
$result[$i] = $newArray;
$i++;
}
}
$response -> result = $result;
$response -> rows = $i;
return $response;
}

Categories