Create an array inside array in PHP - php

I have an imaging web service where I want to send as a JSon the results of a query in PHP to my application.
Basically, my result contains multiple results with each one having the same and following attributes
id
date
owner
extension
filename
I want to put them inside an array in such a way that each item's result is an array itself inside the bigger array just like the below image.
How can I accomplish this?

Do you need this?
$arrayInArray = array(
array("Thing1","Thing2"),
array("Thing3","Thing4")
);

After your query you can build an array the way you want (these are called multidimensional arrays) by using
$res = mysqli_query("SELECT `xx` FROM `xx`");
$images = array();
while($row = mysqli_fetch_array($res)) {
$images[] = $row;
}
return json_encode($images);

Say you have an image $image which is an array containing your attributes id, filename and so on.
Then just create array that hold all images and push it into that.
$images = [];
$images[] = $image; // Push image into images
// Or if you don't already have $image, you can also create and push at the same time
$images[] = [
'id' => 1,
...
];

You can generate array like this
<?php
$data=[
0=>[
'id'=>1,
'date'=>'3/3/2017',
'owner'=>'ownerName',
'extension'=>'yourExtension',
'filename'=>'YourFileName'
],
1=>[
'id'=>2,
'date'=>'3/3/2017',
'owner'=>'ownerName',
'extension'=>'yourExtension',
'filename'=>'YourFileName'
]
];
$jsonData=json_encode($data)//convert into jsondata to send
?>
Then send this data.

This is called multidimensional array , simple syntax for your requirement is
Array(
[0] => Array
(
[id] => 1,
[date] => 2021,
[owner] => 'shebin',
[extension] => 'png',
[filename] => 'new'
)
)
In order to get the above structure you can simply use :
In this example ,
consider $images as multidimensional array so code will be like
$images[0]['id'] = 1 ;
$images[0]['date'] = 2021 ;
$images[0]['owner'] = 'shebin' ;
$images[0]['extension'] = 'png' ;
$images[0]['filename'] = 'new' ;
Instead of 0 you can use variable so you can create multiple set of this array
$images[$i]['id'] = 1 ;

Related

How to Reference/pull/sort by a specific key in a multidimensional array

I am writing a page that pulls images and image data out of a multidimensional array. I need to be able to click a button that calls a function to sort out the images by tags(IE tag_GlassDoor & tag_GlassWall) - basically to show only images that do or do not have that particular element (in this case im using 0 and 1 for yes and no), such as a glass door. I can currently make that array display the data, but I cant figure out how to sort the data by one of the array keys, or even really the syntax to pull a single value out at will.
$arrImages[] =
[
'img_sm'=>'image1.jpg',
'tag_GlassDoor'=>0,
'tag_GlassWall'=>1,
];
$arrImages[] =
[
'img_sm'=>'image2.jpg',
'tag_GlassDoor'=>1,
'tag_GlassWall'=>1,
];
Filtering is the answer, it can be used to filter one dimensional Arrays and multidimensional arrays.
the general implementation would be something like this:
$arr = array(
array(
'image' => "data",
'hasObject' => 1
),
array(
'image' => "data",
'hasObject' => 0
),
);
$finteredArray = array_filter($arr, function ($r) {
return (bool) $r['hasObject'];
});
print_r($finteredArray);
// it outputs:
// Array ( [0] => Array ( [image] => data [hasObject] => 1 ) )

Show images based on String

i want my code to show certain images based on a given string like "Brand1,Brand2,Brand3"
I already declared the images with:
<?php
$brandString ="Brand1,Brand2,Brand3";
$images = [
'Brand1' => 'Brand1.png',
'Brand2' => 'Brand2.png',
'Brand3' => 'Brand3.png',
'Brand4' => 'Brand4.png'
];
Now I only want to show the images that are declared in the string. What is the best way to do this?
Using explode, you can split the string into an array on every occurance of a comma. That way you can just run through your brand array by using foreach.
So, using your example it would look something like this:
<?php
$brandString ="Brand1,Brand2,Brand3";
$brandArray = explode(",", $brandString);
$images = [
'Brand1' => 'Brand1.png',
'Brand2' => 'Brand2.png',
'Brand3' => 'Brand3.png',
'Brand4' => 'Brand4.png'
];
foreach($brandArray AS $brand) {
echo $images[$brand]; //this would print out the image names in order: Brand1.jpg, Brand2.jpg, Brand3.jpg
}

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

Create an object from a valid JSON array with php

I know my JSON is valid, I'm wanting to pull all the KEY's out of the array and put them in an object. However it seems I can either access ONE objects Key or Value, the entire array, or one key value pair. I have not figured out how to parse out all the keys, or all the values in the array.
Here is what I've tried:
print_r($json_obj) yields:
Array ( [0] => Array ( [0] => uploads/featured/doublewm-4097.jpg [1] => featured ) [1] => Array ( [0] => uploads/featured/moon-5469.jpg [1] => featured ) )
print_r($json_obj[0][1]) yields:
featured
print_r($json_obj[1][0]) yields:
uploads/featured/moon-5469.jpg
print_r($json_obj[1][1]) yeilds:
featured
print_r($json_obj[0][0]) yields:
uploads/featured/doublewm-4097.jpg
PHP Code:
<?php
$resultSet = '[["uploads/featured/doublewm-4097.jpg","featured"],
["uploads/featured/moon-5469.jpg","featured"]]';
$json_obj = json_decode($resultSet);
// print_r($json_obj);
print_r($json_obj[0][1]);
?>
The JSON validates per JSONLint
[
[
"uploads/featured/doublewm-4097.jpg",
"featured"
],
[
"uploads/featured/moon-5469.jpg",
"featured"
]
]
I would like to end up with a object with all the keys in the json_obj... ie:
json_obj = array(
'uploads/featured/moon-5469.jpg',
'uploads/featured/doublewm-4097.jpg'
);
If your input is always in the same format, you can handle it like this
$tmp = json_decode($resultSet);
$json_obj = array();
foreach ($tmp as $values) {
array_push($json_obj, $values[0]);
}
This will give you $json_obj in the desired format with a hardcoded $resultSet like the one you provided.
maybe this is what you are looking for:
json encode server-side like:
echo json_encode($html);
json parse clientside like
var str = JSON.parse(data);
alert (JSON.stringify(str))
I managed to fix it like this:
Changing the json object to this format
data = { gallery: gallery_name,
files: [
// imagefile,imagefile,imagefile...
]
};
And the using the following php
$resultSet = json_decode($_GET['submittedResults'], true);
$gallery = $resultSet['gallery'];
$files_to_zip = $resultSet['files'];

PHP array : simple question about multidimensional array

i've got a SQL query which returns multiple rows, and i have :
$data = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
which is perfect, but only if my query returns one row.
i tried that :
$data = array();
$data[$row['nom']]["nom"] = $row['nom'] ;
...
$data[$row['nom']]['average'] = "$moyenne_ge";
in order to have :
$data[brand1][nom] = brand1
$data[brand1][average] = 150$
$data[brand2][nom] = brand2
$data[brand2][average] = 20$
...
but when i do : json_encode($data)
i only have the latest JSON object instead of all JSON object from my request as if my array has only one brand instead of 10.
I guess i did something stupid somewhere.
Thanks for your help
I'd guess that your line:
$data = array();
Is initializing the array on each iteration of your loop. You aren't accumulating more than one row of data.
I guess something like this should work for you:
$resource = mysql_query("YOUR QUERY");
$results = array()
while($result = mysql_fetch_assoc($resource)) {
$results[$result['brand']] = array(
'nom' => $result['nom'],
'prix' => $result['rapport'],
'average' => $moyenne_ge
);
)
$results now contains all the rows from the query indexed by brand. Ask in comments if this wasn't what you're looking for.
If I am reading you right, you should just have to do something like this:
$data[] = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
(notice the [])
This should append each array onto $data instead of overwriting the contents.

Categories