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];
}
Related
Here is my array:
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
I need to restart all keys and start all of them from 0. Based on some researches, I figured out I have to use array_values() function. But it just makes the keys of outer array re-index, See.
How can I apply it on the all keys of array? (even nested ones)
You can use array_values + recursively calling custom function:
function arrayValuesRecursive($array) {
$array = array_values($array);
$countValues = count($array);
for ($i = 0; $i < $countValues; $i++ ) {
$subElement = $array[$i];
if (is_array($subElement)) {
$array[$i] = arrayValuesRecursive($subElement);
}
}
return $array;
}
$restructuredArray = arrayValuesRecursive($array);
You can implement it using recursion like this:
function reIndex($arr) {
$arr = array_values($arr);
foreach ($arr as $k => $v) {
if (is_array($v)) {
$arr[$k] = reIndex($v);
}
}
return $arr;
}
$arr = reIndex($arr);
Hi checkout following code
<?php
$arr = [
1 => [
2 => "something",
3 => "something else"
],
2 => "foo br"
];
$reIndexedArray = array();
foreach($arr as $arrItr){
$reIndexedArray[] = count($arrItr) > 1 ? array_values($arrItr) : $arrItr;
}
print_r($reIndexedArray);
?>
output is
Array
(
[0] => Array
(
[0] => something
[1] => something else
)
[1] => foo br
)
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
)
)
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
In the code below, I'm pulling apart a CSS file and trying to return in an array. It's working, but my formatting looks weird. What did I do wrong?
Sample of what I'm looking for:
Array
(
[body] => Array
(
[width] => 100%
[background-color] => #e6e6e6
)
)
My code:
$file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '../parse-css-upload/' . $this->newFileName);
$element = explode('}', $file);
$css_array = array(); // master array to hold all values
$element = explode('}', $file);
foreach ($element as $element) {
// get the name of the CSS element
$a_name = explode('{', $element);
$name = $a_name[0];
// get all the key:value pair styles
$a_styles = explode(';', $element);
// remove element name from first property element
$a_styles[0] = str_replace($name . '{', '', $a_styles[0]);
// loop through each style and split apart the key from the value
$count = count($a_styles);
for ($a=0;$a<=$count;$a++) {
if ($a_styles[$a] != '') {
$a_key_value = explode(':', $a_styles[$a]);
// build the master css array
$css_array[$name][$a_key_value[0]] = $a_key_value[1];
}
}
}
Actual outpt:
Array
(
[body, html ] => Array
(
[
width] => 100%
[
background-color] => #e6e6e6
[
] =>
)
[
body ] => Array
(
[
font-family] => "Open Sans", sans-serif
[
color] => #686868
[
font-size] => 16px
[
font-weight] => 300
[
line-height] => 1.7
[
] =>
)
Try :
$css_array[$name][trim($a_key_value[0])] = trim($a_key_value[1]);
You have new line characters around.
Try this hope this will help
for ($a=0;$a<=$count;$a++) {
if (trim($a_styles[$a]) != '') {
$a_key_value = explode(':', $a_styles[$a]);
// build the master css array
$css_array[trim($name)][trim($a_key_value[0])] = trim($a_key_value[1]);
}
}
Use trim in your code
I have to create a array dynamically like I have a method which will pass keys and based on those keys I need to create arrays inside them
Format will be like-
{
"TEST1":{
"140724":[
{
"A":"1107",
"B":4444,
"C":"1129",
"D":"1129"
},
{
"A":"1010",
"B":2589,
"C":"1040",
"D":"1040"
}
],
"140725":[
]
}
}
So how should I frame this logic inside for loop. I am new to php so formatting the same creating trouble.
$json_Created = array("TEST1" => array());
foreach($val as $key=>$value){
array_push($json_created,array($key = array()));
}
The entire array is dynamic, so like I have 140724 ,,, till 140731 (actually date format yymmdd), any amount if numbers can be considered. SO that part is dynamic moreover some dates may be wont have any values and some will have.
So my main point is to develop that logic so that irrespective the
number of inputs , my array formation must be intact.
You can use json_encode with array to do so
$array = array(
"TEST1" => array(
"140724" => array(
array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
),
array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
)
),
"140725" => array(
)
)
);
echo json_encode($array);
Another way to construct array is
$array = array();
$array["TEST1"]["140724"][] = array(
"A" => "1107",
"B" => "4444",
"C" => "1129",
"D" => "1129"
);
$array["TEST1"]["140724"][] = array (
"A" => "1010",
"B" => "2589",
"C" => "1040",
"D" => "1040"
);
$array["TEST1"]["140725"] = array();
echo json_encode($array);
Finally managed to write the code-
$keys_content = array("starttime", "id", "duration", "endtime");
$dates = array();//140724,140725,140726140727
$mainID =“TEST1”;
$arraySuperMain = array();
$arrayMain = array();
for ($j = 0; $j < count($dates); $j++) {
$array_main = array();
$subset = array();
for ($i = 0; $i < count($keys_content); $i++) {
$key = $keys_content[$i];
$subset = array_push_assoc($subset, $key, "Value".$i);
}
$array_main = array_push_assoc($array_main, $dates[$j], $subset);
array_push($arrayMain, $array_main);
}
$createdJSON = array_push_assoc($arraySuperMain, $mainID, $arrayMain);
public static function array_push_assoc($array, $key, $value) {
$array[$key] = $value;
return $array;
}