How to print array in PHP with unknown number of elements - php

I am having a very strange issue with printing out element of an array.
I am attempting to print out some elements of an array inside of a php foreach Here is exactly what the array looks like
[2] => Array
(
[id] => 3
[body] => dsfgdfgd
[has_subquestion] => 1
[is_subquestion] => 0
[ordering] => 2
[is_manditory] => 0
[created] => 2013-01-09 12:06:47
[parent_id] => 0
[sub] => Array
(
[0] => Array
(
[id] => 4
[body] => dfgdfg
[has_subquestion] => 1
[is_subquestion] => 1
[ordering] => 0
[is_manditory] => 0
[created] => 2013-01-09 11:24:20
[parent_id] => 3
)
[1] => Array
(
[id] => 23
[body] => gsdgdf
[has_subquestion] => 1
[is_subquestion] => 1
[ordering] => 14
[is_manditory] => 0
[created] => 2013-01-09 12:56:33
[parent_id] => 3
)
)
)
[3] => Array
(
[id] => 5
[body] => dfgdfg
[has_subquestion] => 1
[is_subquestion] => 0
[ordering] => 3
[is_manditory] => 0
[created] => 2013-01-09 12:06:47
[parent_id] => 0
[sub] => Array
(
[id] => 6
[body] => dfgdfg
[has_subquestion] => 0
[is_subquestion] => 1
[ordering] => 3
[is_manditory] => 0
[created] => 2013-01-08 13:37:07
[parent_id] => 5
)
)
Notice that the first one has 2 [sub]'s and the second only has one. This is my code for printing them
echo count($question['sub']);
foreach($question['sub'] as $s):
echo '<li>
<input type="hidden" name="sub[id]" value="'. $s['id'] .'" />
<input type="hidden" name="sub[parent]" value="'. $question['id'] .'" />
'. $s['body'] .'</li>';
endforeach;
this is what it is printing
2
dfgdfg
gsdgdf
8 <--count (which should be 1 not 8)
6 <--each of the following are the first letter/number in the sub array
d
0
1
3
0
2
Can anyone see what I am doing wrong?

Run
print_r($array).
It should also give you your answer in recursive fashion

You will need to update your code to see if the [sub] array is multidimensional or not. I would do it by checking if sub has a key that will only match if there is only a single array:
if (array_key_exists('id', $question['sub']) {
// This is a single array so wrap it in an array so that the foreach logic works
$question['sub'] = array($question['sub']);
}
... continue as normal with your foreach loop.

use is_array() and call the function recursivly ?

Related

search inside arrays with condition in php

I have an api with a list of arrays inside one array and each array inside this array it has one key [attributes] and inside this key one array with key [CITY_NAME]
this is my array coming from api
this array number is 0 but every day this number is changed and my figures come wrong, what is the good way to always have my city figures using the key [CITY_NAME]
I am fetching the data using this code
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$data = $json_data['features'];
$mycity = $data[0]['attributes'];
Array
(
[0] => Array
(
[attributes] => Array
(
[CITY_NAME] => city1
[Name] => city1
[ADMIN_NAME] => city1
[POP_CLASS] => 5,000,000 to10,000,000
[Population] => 7676654
[Population_Data_Source] => Wikipedia
[Population_Data_Date] => 2018
[CityID] => 14
[Longitude] => 46.7614868685786
[Latitude] => 24.7388786516234
[Confirmed] => 0
[Recovered] => 0
[Deaths] => 0
[Active] => 0
[Tested] => 0
[Name_Eng] => city1
[Join_Count] => 61
[Confirmed_SUM] => 5152
[Deaths_SUM] => 9
[Recovered_SUM] => 1407
[Active_SUM] => 3736
[Tested_SUM] => 376607
[ObjectId] => 14
)
)
[1] => Array
(
[attributes] => Array
(
[CITY_NAME] => city2
[Name] => city2
[ADMIN_NAME] => city2
[POP_CLASS] => 1,000,000 to 5,000,000
[Population] => 1675368
[Population_Data_Source] => Wikipedia
[Population_Data_Date] => 2010
[CityID] => 9
[Longitude] => 39.8148987363852
[Latitude] => 21.4273876500039
[Confirmed] => 0
[Recovered] => 0
[Deaths] => 0
[Active] => 0
[Tested] => 0
[Name_Eng] => city2
[Join_Count] => 59
[Confirmed_SUM] => 6848
[Deaths_SUM] => 85
[Recovered_SUM] => 1145
[Active_SUM] => 5618
[Tested_SUM] => 0
[ObjectId] => 9
)
)
Since I may have misunderstood and you may have many, just build a new array with CITY_NAME:
foreach($data as $values) {
$result[$values['attributes']['CITY_NAME']] = $values['attributes'];
}
Now you can access by CITY_NAME:
echo $result['city1']['Population'];
This might be easier. Extract all attributes from all arrays into an array, then create an array from that indexed by CITY_NAME:
$data = array_column(array_column($json_data['features'], 'attributes'),
null, 'CITY_NAME');

How to delete array of array if particular key doesn't exist in it?

I have collection of array and i want delete array of array where "answer_id" key is not exits.
my array look like this.
Array
(
[0] => Array
(
[question_no] => 1
[subject_id] => 1
[question_id] => 255
[currect_ans_id] => 2657
[time_taken] => 110
[is_visited] => 1
[is_saved] => 0
[answer_id] => 2659
)
[1] => Array
(
[question_no] => 2
[subject_id] => 1
[question_id] => 256
[currect_ans_id] => 2662
[time_taken] => 0
[is_visited] => 1
[is_saved] => 0
)
)
and want array like this(where answer_id key exits).
Array
(
[0] => Array
(
[question_no] => 1
[subject_id] => 1
[question_id] => 255
[currect_ans_id] => 2657
[time_taken] => 110
[is_visited] => 1
[is_saved] => 0
[answer_id] => 2659
)
)
You can use array_filter to remove entries which don't have an answer_id:
$output = array_filter($input, function ($a) { return isset($a['answer_id']); });
Demo on 3v4l.org

Sort an associative array with custom order [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
How can we sort an associative array with custom order?
My array look like this
Array
(
[pa_color] => Array
(
[name] => pa_color
[value] =>
[position] => 0
[is_visible] => 1
[is_variation] => 1
[is_taxonomy] => 1
)
[pa_dimension] => Array
(
[name] => pa_dimension
[value] =>
[position] => 1
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travel-duration] => Array
(
[name] => pa_travel-duration
[value] =>
[position] => 2
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travel-type] => Array
(
[name] => pa_travel-type
[value] =>
[position] => 3
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_travelling-with] => Array
(
[name] => pa_travelling-with
[value] =>
[position] => 4
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_volume] => Array
(
[name] => pa_volume
[value] =>
[position] => 5
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
[pa_weight] => Array
(
[name] => pa_weight
[value] =>
[position] => 6
[is_visible] => 1
[is_variation] => 0
[is_taxonomy] => 1
)
)
and i want this array is like pa_travel-duration first pa_volume second ?? I know there is a native php function usort but i could not understand this.
This will do the work, but im pretty sure there's much better ways to do it:
Code:
$array = array("pa_color" => "color",
"pa_dimension" => "dimension",
"pa_travel-duration" => "Random Stuff: " . rand(100,999),
"pa_volume" => "volumen"
);
$tmp = array("pa_travel-duration" => $array["pa_travel-duration"],
"pa_volume" => $array["pa_volume"],
);
unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);
print_r($array);
Result:
Array
(
[pa_travel-duration] => Random Stuff: 127
[pa_volume] => volumen
[pa_color] => color
[pa_dimension] => dimension
)
Take care because if the array doesn't have the proper key it will throw an error, you need to add few checks there.
$sort_by = array('pa_travel-duration', 'pa_volume', 'pa_color','pa_dimension','pa_travel-type','pa_travelling-with','pa_weight');
$temp_arr = array();
foreach ($sort_by as $key) {
$temp_arr[$key] = $data[$key];
}
$data = $temp_arr;
echo '<pre>'; print_r($data);
Define your order in $sort_by array

How to access stdClass element in php ?

I query db and I have an array. How can I access stdClass object ? And I want also serializedName property like in java serializedName. So, The fields which query from db must be assign with my custom object class fields.How can I use this?
Array
(
[0] => stdClass Object
(
[receipt_id] => 1
[defect] => asd
[tec_report] => sad
[doc_number] => asd
[warrant] => 12
[warrant_start] => 2016-01-05
[warrant_end] => 2016-01-29
[repair_time] => 3
[receipt_date] => 2016-01-05
[delivery_date] =>
[service_type_id] => 0
[service_price] => 0
[part_price] => 0
[pay_type] =>
[labour] => 0
[summary] => 0
[technician_id] =>
[customer_id] => 0
[device_id] => 0
[seri_number] =>
)
[1] => stdClass Object
(
[receipt_id] => 2
[defect] => asdsad
[tec_report] => asds
[doc_number] =>
[warrant] =>
[warrant_start] =>
[warrant_end] =>
[repair_time] =>
[receipt_date] => 2016-01-05
[delivery_date] =>
[service_type_id] => 1
[service_price] => 12
[part_price] => 12
[pay_type] =>
[labour] => 12
[summary] => 12
[technician_id] =>
[customer_id] => 21
[device_id] => 12
[seri_number] =>
)
)
try this for one by one
echo $array[0]->receipt_id;
try this :
foreach($yourArray as $val){
echo $val->receipt_id;
echo "<br/>".$val->defect;
}

Tree listing for categorys

I have an array like this
Array
(
[0] => stdClass Object
(
[cat_id] => 3
[cat_name] => sample 3
[cat_description] =>
[cat_folder] => sample_3
[cat_path] => sample_3
[cat_parent] => 0
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
[1] => stdClass Object
(
[cat_id] => 2
[cat_name] => sample 2
[cat_description] =>
[cat_folder] => sample_2
[cat_path] => sample_3/sample_2
[cat_parent] => 3
[cat_num_files] => 0
[cat_num_files_total] => 0
[cat_user_roles] =>
[cat_owner] => 1
[cat_icon] =>
[cat_exclude_browser] => 0
[cat_order] => 0
)
)
I need to list these like
-sample 3
--sample 2
---sample 4
There is no limit for the link depth, a category may have 5 deep, it may be 10. I have tried this in a foreach loop but failed to retrieve a list like a tree.
I recommend recursion, becouse you don't know how nested it will be. Bellow is example of recursion function.
function genCat($parentCat){
echo $parentCat->name;
if ($parentCat->haveChildren){
foreach($parentCat->children as $child){
genCat($child);
}
}
}
This is just example, hope it helps

Categories