Display element from array before looping - php

I need to display a certain object from an array before showing the rest of the array.
The array looks like this:
Array
(
[0] => stdClass Object
(
[template_id] => 91
[template_name] => Alphabet
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821665
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[1] => stdClass Object
(
[template_id] => 92
[template_name] => Blank Template
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821670
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[2] => stdClass Object
(
[template_id] => 31
[template_name] => Holiday Specials
[template_thumbnail] => accommodation-1-20110926.jpg
[template_create_date] => 1456821660
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => Accommodation
[sort] => 3
)
)
I need to show Blank Template first and then show the rest alphabetically (the order it is in now.
Is there a more elegant solution than looping through the array twice? The size of the array can be anything from 1 (the blank template) to countless objects.

$str="";
for($i=0;$i<=count($arr);$i++){
if($arr[$i]['template_name'] == "Blank Template"){
echo $arr[$i]['template_name'];
}else{
$str .= $arr[$i]['template_name']. "<br>";
}
}
echo $str;

Try this:
$firstItem = null;
$outArray = [];
foreach($yourArray as $item){
if($item->template_name == 'Blank Template'){
$firstItem = $item;
}else{
$outArray[$item->template_name] = $item;
}
}
ksort($outArray,SORT_STRING);
array_unshift($outArray,$firstItem);
Just one loop. Pay attention that this way of doing things, just work if you have uniqueness on the template_name!
Hope it helps.

This will work for you, try
<?php
$dataArray = array(0=>array('template_id'=>91,'template_name'=>'Alphabet'),
1=>array('template_id'=>92,'template_name'=>'Blank Template'),
2=>array('template_id'=>31,'template_name'=>'Holiday Specials')
);
$newArray = array();
foreach($dataArray as $key => $val)
{
if(in_array('Blank Template',$val))///find the key for black template
{
unset($dataArray[$key]); ///unset black temp from original array
$newArray[] = $val;///push black temp into new array at 0 index
foreach($dataArray as $k => $v)
{
$newArray[] = $v; ///push the renaming values into new array
}
}
}
echo "<pre>"; print_r($newArray);
?>
This will give you :
Array
(
[0] => Array
(
[template_id] => 92
[template_name] => Blank Template
)
[1] => Array
(
[template_id] => 91
[template_name] => Alphabet
)
[2] => Array
(
[template_id] => 31
[template_name] => Holiday Specials
)
)
LIVE EXAMPLE : CLICK HERE

Related

How can i filter a multidimensional array into another one in PHP?

probably this question is duplicate because I don't know how to describe the problem to find an answer.
I've got an array with 3 parameters: date, events and tags.
A date contains a unix timestamp,
An events is an arrya that contain events' id,
Tags is an array that contain events' tags (comma-separated string if the number is not alone).
This is the array:
Array
(
[date] => 1554328800
[events] => Array
(
[0] => 130
[1] => 131
[2] => 163
)
[tags] => Array
(
[0] => 4
[1] => "1,3,4"
[2] => "1,3"
)
)
The relationship between events and tags is in the key, so the event 130 that has position 0 has tag 4.
As you can see there are some tags repeated (events 130 and 131 or 131 and 163).
How could I get an array with only repeated events like this:
Array
(
[0] => Array
(
[date] => 1554328800
[events] => Array
(
[0] => 130
[1] => 131
)
[tags] => 4
)
[1] => Array
(
[date] => 1554328800
[events] => Array
(
[0] => 131
[1] => 163
)
[tags] => Array
(
[0] => 1
[1] => 3
)
)
)
Here is how I would do it:
List the events per individual tag
This will give several sets of events, which can be used in the next step
List the tags per set of events that occurred in previous step
Produce the result from step 2
Here is the code, also runnable at 3v4l.org:
// Sample input
$data = [
"date" => 1554328800,
"events" => [130, 131, 163],
"tags" => [4, "1,3,4", "1,3"]
];
// 1. List the events per individual tag
foreach($data["tags"] as $i => $val) {
$vals = explode(",", $val);
foreach($vals as $val) {
$eventsByTag[$val][] = $data["events"][$i];
}
}
// 2. List the tags per set of events
foreach($eventsByTag as $tag => $events) {
sort($events, SORT_NUMERIC);
$tagsByEvents[implode(",", $events)][] = $tag;
}
// 3. produce the result
foreach($tagsByEvents as $events => $tags) {
$events = explode(",", $events);
if (count($tags) == 1) $tags = $tags[0];
$result[] = [
"date" => $data["date"],
"events" => $events,
"tags" => $tags
];
}
print_r($result);
$date = array();
$date['date'] = 1554328800;
$date['events'] = array(130, 131, 163);
$date['tags'] = array(4, "1,3,4", "1,3");
$events_by_tag = array(); //gather events grouped by tag
foreach ($date['events'] as $pos => $event) { //parse all events
if (is_string($date['tags'][$pos])) { //if tag is a string <=> if there are more than one tag for the current event
$tags = explode(',', $date['tags'][$pos]); //explode string to loop over the tags
foreach ($tags as $tag) {
if (is_array($events_by_tag[$tag])) { //if tag has already been found and then an array exists to store it
array_push($events_by_tag[$tag], $event);
} else {
$events_by_tag[$tag] = array($event); //else create an array for the next times this tag will be found and store it inside
}
}
} else { //if there's a single tag which is a integer
if (is_array($events_by_tag[$tag])) { //if tag has already been found and then an array exists to store it
array_push($events_by_tag[$date['tags'][$pos]], $event);
} else {
$events_by_tag[$date['tags'][$pos]] = array($event); //else create an array for the next times this tag will be found and store it inside
}
}
}
$result_array = array(); //final array reorganized + date
foreach ($events_by_tag as $tag => $events) {
$tmp_array['date'] = $date['date'];
$tmp_array['events'] = $events;
$tmp_array['tags'] = $tag;
array_push($result_array, $tmp_array);
}
This is NOT exactly what you expected because it will not merge events sharing tags. I think this part needs another post to be developed, but otherwise I can modify my answer to give you the way to go if necessary.
pl check this
$sarr=['date'=>1554328800,
'events'=>
[
130,
131,
163
],
'tags'=>
[
4,
"1,3,4",
"1,3"
]
];
$tagarr=[];
$events=$sarr['events'];
$index=0;
foreach( $sarr['tags'] as $tag)
{
$t=explode(",",$tag);
$cnt=count($t);
for($idx=0;$idx<$cnt;$idx++)
$tagarr[$t[$idx]][]=$events[$index];
$index++;
}
$cnt=count($tagarr);
$myarr=[];
foreach($tagarr as $key=>$value)
{
$myarr[]=['date'=>$sarr['date'],'events'=>$value,'tags'=>$key];
}
ec ho "<pre>";
print_r($myarr);
echo "</pre>";
output is
Array
(
[0] => Array
(
[date] => 1554328800
[events] => Array
(
[0] => 130
[1] => 131
)
[tags] => 4
)
[1] => Array
(
[date] => 1554328800
[events] => Array
(
[0] => 131
[1] => 163
)
[tags] => 1
)
[2] => Array
(
[date] => 1554328800
[events] => Array
(
[0] => 131
[1] => 163
)
[tags] => 3
)
)

Get Array value based on object ids with php

I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}

Taking out just one value from an array

I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

How to iterate over a multidimensional array?

I have array like this. This array is created dynamically
Array
(
[Data NotUploading] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => A
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
[1] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
)
)
[Battery Problem] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-03
[issue_id] => 3
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Battery Problem
)
)
)
)
What I need to do is to use 2 foreach or 1 foreach & 1 for loop so that I can get each value of date I did like this
foreach($gResultbyName as $key1 => $rec){
for($j = 0;$j<count($rec);$j++ ){
echo $rec['items'][$j]['date'];
}
}
but its only retrieving 2013-04-02 & 2013-04-03 that is 0 index date of data NotUploading & 0 index date of Battery Problem. Basically I need to compare each value and others stuff but I just cant get each date value.
Forgive me for ignorance but I tried a lot :(
try this:
foreach ($data as $d)
{
foreach($d['items'] as $item)
{
echo $item['date'];
}
}
Your for-loop loops count($rec) times, but should count($rec['items']).
This should load the dates into an array sorted by the issue_name. The you can step through them for further processing.
$dates= array();
foreach ($gResultbyName AS $events){
foreach ($events['items'] AS $item){
$dates[$item['issue_name']][] = $item['date'];
}
}
var_dump($dates);

Categories