How do i fill an objects attributes dynamically? - php

I am trying to save an object with a variable amount of "cols". The number of cols is equal to the number of headers. This is how the code looked before:
if(isset($_POST['submit'])){
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
$sub->col1 = $_POST['col1'];
$sub->col2 = $_POST['col2'];
$sub->col3 = $_POST['col3'];
$sub->col4 = $_POST['col4'];
$sub->col5 = $_POST['col5'];
$sub->col6 = $_POST['col6'];
$sub->col7 = $_POST['col7'];
$sub->col8 = $_POST['col8'];
$sub->col9 = $_POST['col9'];
$sub->col10 = $_POST['col10'];
$sub->col11 = $_POST['col11'];
$sub->col12 = $_POST['col12'];
$sub->col13 = $_POST['col13'];
$sub->col14 = $_POST['col14'];
$sub->col15 = $_POST['col15'];
This is how I want it to look:
if(isset($_POST['submit'])){
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
$i = 0;
foreach($headers as $header){
$i++ ;
$sub->col.$i = $_POST['col'.$i];
}
How do I pass the variable $i into the object's attributes? $sub->(col.$i) ? $sub->(col{$i}) ? Please help me figure this out =) Thank you

Try this:
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
for($i = 1; $i <= count($headers); ++$i)
$sub->{'col' . $i} = $_POST['col' . $i];
But, this is really not the way that the columns should be stored in the Sub object, you should use an array:
$sub->columns = array();
for($i = 1; $i <= count($headers); ++$i) {
$sub->columns[] = $_POST['col' . $i];
}

You have to use {} :
$sub->{'col' . $i} = ...

$field = "col$i";
$sub->$field = "whatver"

I'd prefer a setter method.
class Sub {
public function set($attribute, $value) {
$this->$attribute = $value;
}
}
Now you can do:
foreach($_POST as $key => $value) {
$sub->set($key, $value)
}
Or without the loose coupling:
$i = 1;
while($value = $_POST['col' . $i]) {
$sub->set('col' . $i, $value);
$i++;
}

Related

php array keep pushing in the depth

My current code is like :
<?php
$item = "123.456.789.963.852.741";
$item_arr = explode(".", $item);
$inner_count = count($item_arr);
$parent_element = "myarray";
if($inner_count==3){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]);
}
if($inner_count==4){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]);
}
if($inner_count==5){
$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]['order'] = $count;
$my_array[$parent_element]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]=$my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]];
unset($my_array[$item_arr[0]]['XYZ-Key'][$item_arr[1]]['XYZ-Key'][$item_arr[2]]['XYZ-Key'][$item_arr[3]]['XYZ-Key'][$item_arr[4]]);
}
now i want to extend it to more count (right now code is up to 5)
but the problem I can not the code in the same way
You can do it in this manner. Just change string for your format
$item = "1.2.3.4.5";
$ar = explode('.', $item);
$start = '{';
$end = '}';
foreach($ar as $i) {
$start .= '"'.$i.'":{';
$end = '}'.$end;
}
$temp = $start . '"order":{}' .$end; // {"1":{"2":{"3":...{"order":{}}}}}
$res = json_decode($temp,true);

PHP look-and-say sequence

I'm trying to code Conway look-and-say sequence in PHP.
Here is my code:
function look_and_say ($number) {
$arr = str_split($number . " ");
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
return $res;
}
As I run the function, look_and_say(9900) I am getting value I expected: 2920.
My question is for assigning $arr to be $arr = str_split($number) rather than $arr = str_split($number . " "), the result omits the very last element of the $arr and return 29.
Is it normal to add empty space at the end of the $arr foreach to examine the last element or is there any better way to practice this code - besides regex way.
There are 2 methods I was able to come up with.
1 is to add concatenate at the result after the loop too.
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
foreach($arr as $num){
if($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
}
$res .= $count . $target;
return $res;
}
And the 2nd one is to add another if clause inside the loop and determine the last iteration:
function look_and_say ($number) {
$arr = str_split($number);
$target = $arr[0];
$count = 0;
$res = "";
$i=0;
$total = count($arr);
foreach($arr as $num){
if($i == ($total-1))
{
$count++;
$res .= $count . $target;
}
elseif($num == $target){
$count++;
}else{
$res .= $count . $target;
$count = 1;
$target = $num;
}
$i++;
}
return $res;
}
I want to suggest you other way using two nested while loops:
<?php
function lookAndSay($number) {
$digits = str_split($number);
$result = '';
$i = 0;
while ($i < count($digits)) {
$lastDigit = $digits[$i];
$count = 0;
while ($i < count($digits) && $lastDigit === $digits[$i]) {
$i++;
$count++;
}
$result .= $count . $lastDigit;
}
return $result;
}

Laravel show array json

I want to show data from database: for every id_grup has many lapangan(court)
$groups_resource = Groups::all();
$groups = [];
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$g->children = array();
$groups[] = $g;
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$g->children[] = $l;
}
}
return json_encode($groups);
output for above code
[{"id_group":"Group_1","name":"Lapangan Badminton","expanded":true,"eventHeight":25,"children":[]},{"id_group":"Group_2","name":"Lapangan Tenis","expanded":true,"eventHeight":25,"children":[]}]
There is no value for children which might be like this.
[{"id":"group_1","name":"Indoor","expanded":true,"eventHeight":25,"children":[
{"id":"1","name":"Court 1"},
{"id":"2","name":"Court 2"},
{"id":"3","name":"Court 3"},
{"id":"4","name":"Court 4"}]},"id":"group_2","name":"Outdoor","expanded":true,"eventHeight":25,"children":[
{"id":"11","name":"Court 5"},
{"id":"12","name":"Court 6"},
{"id":"13","name":"Court 7"},
{"id":"14","name":"Court 8"}]}]
You are using wrong array braces. You shouldn't first initialize the children property of a group instead of that you can do it like this:
foreach($groups_resource as $group)
{
$g = new Groups();
$g->id_group = "Group_".$group['id_group'];
$g->name = $group['nama'];
$g->expanded = true;
$g->eventHeight = 25;
$l_arr = [];
$lapangan_resource = Lapangan::with('groups')->orderBy('nama')->get();
foreach($lapangan_resource as $lapangan)
{
$l = new Lapangan();
$l->id_lapangan = $lapangan['id_lapangan'];
$l->name = $lapangan['nama_lapangan'];
$l_arr[] = $l;
}
$g->children = $l_arr;
$groups[] = $g;
}
return json_encode($groups);
Hope this helps!

how to use the for loop to extract data from a list of url using php

The for loop in the code below does not work properly.
$html= #file_get_html($url);
$job_array = array();
foreach($html->find('a') as $link) {
// $links=$html->find('a');
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . "<br/>";
}
for ($a = 0; $a <= ($link->href); $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
I think
$link->href
isn't a number and the for loop can't use a non-number to compare $a to and iterate over. Perhaps you can do:
$html= #file_get_html($url);
$job_array = array();
$myNumberToIterateWith = 0;
foreach($html->find('a') as $link) {
// $links=$html->find('a');
$myNumberToIterateWith++;
if (strpos($link->href, '/job-category/') !== false) {
$job_array[] = $link->href . " ";
}
for ($a = 0; $a <= $myNumberToIterateWith; $a++) {
//$page_number = 20;
// for ($i = 1; $i <= $page_number; $i++) {
$html2 = file_get_html($link->href);
$response = array();
foreach ($html2->find('div#mainContent') as $header) {
$response[] = $header->innertext . "<br/>";
print_r($response);
}
}
Though I'm not sure what you wish the result to be. It is helpful to provide clues as to what you wish to accomplish with the code.

array_multisort how to mount with foreach

I need to mount an array_multisort with the values from one array.
I tryied to mount a string concated and call on the array_multidimensional like here:
function ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias){
$total_vehiculos=count($matriz_up[id_vehiculo]);
//resetear las keys de vehiculos para coger bien los kms y asignarlos
$a_vehiculo_distancia = array_values($m_vehiculo_distancias);
$ordenar = array();
foreach ($a_vehiculo_distancia as $key) {
$ordenar[] = $key;
}
sort($m_vehiculo_distancias);
$string= "";
$ultim_key = end(array_keys($matriz_up));
foreach ($matriz_up as $key => $valor) {
if ($key != $ultim_key) $string.= $matriz_up[$key].',';
else $string.= $matriz_up[$key];
$aaa = '$matriz_up[$key]';
}
echo $string;
echo "<br>";
array_multisort($ordenar, SORT_ASC, $string);
for($i=0;$i<$total_vehiculos;$i++){
$matriz_up['cercanos'][$i] = $m_vehiculo_distancias[$i];
echo $matriz_up['id_vehiculo'][$i]."<br>";
echo $matriz_up['fecha_gps'][$i]."<br>";
echo $matriz_up['id_tipo_posicion'][$i]."<br>";
echo $matriz_up['cercanos'][$i]."<br>";
echo $matriz_up['vaina'][$i]."<br>";
echo "------------<br>";
}
return $matriz_up;
}
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
ordenar_matriz_ultima_posicion_por_distancia($matriz_up,$m_vehiculo_distancias);
With this array_multisort works, but i need to take all the key without put manually..
array_multisort($ordenar, SORT_ASC, $matriz_up['id_vehiculo'], $matriz_up['fecha_gps'], $matriz_up['id_tipo_posicion'], $matriz_up['vaina'] );
Try this code:
<?php
$matriz_up = $m_vehiculo_distancias = array();
$matriz_up['id_vehiculo'][0] = 9;
$matriz_up['fecha_gps'][0] = '2014';
$matriz_up['id_tipo_posicion'][0] = 11111;
$matriz_up['cercanos'][0] = 0;
$matriz_up['vaina'][0] = 12345;
$matriz_up['id_vehiculo'][1] = 3;
$matriz_up['fecha_gps'][1] = '2015';
$matriz_up['id_tipo_posicion'][1] = 22222;
$matriz_up['cercanos'][1] = 0;
$matriz_up['vaina'][1] = 5555;
$matriz_up['id_vehiculo'][2] = 1;
$matriz_up['fecha_gps'][2] = '2016';
$matriz_up['id_tipo_posicion'][2] = 33333;
$matriz_up['cercanos'][2] = 0;
$matriz_up['vaina'][2] = 988;
$matriz_up['id_vehiculo'][3] = 4;
$matriz_up['fecha_gps'][3] = '2017';
$matriz_up['id_tipo_posicion'][3] = 44444;
$matriz_up['cercanos'][3] = 0;
$matriz_up['vaina'][3] = 777;
$m_vehiculo_distancias[9] = 345;
$m_vehiculo_distancias[3] = 712;
$m_vehiculo_distancias[1] = 10;
$m_vehiculo_distancias[4] = 35;
function sortArray($arrayToSortParam, $orderArray)
{
$result = array();
$arrayToSort = $arrayToSortParam;
$keys = array_keys($arrayToSort);
asort($orderArray, true);
$newSort = $cercanos = array();
foreach($orderArray as $key => $value)
{
$newSort[] = array_keys($arrayToSort['id_vehiculo'], $key)[0];
$cercanos[] = $orderArray[$key];
}
foreach($keys as $keyName)
{
uksort($arrayToSort[$keyName], function($key1, $key2) use ($newSort) {
return (array_search($key1, $newSort) > array_search($key2, $newSort));
});
}
$arrayToSort['cercanos'] = $cercanos;
//reset indexes
foreach($keys as $keyName)
{
$arrayToSort[$keyName] = array_values($arrayToSort[$keyName]);
}
return $arrayToSort;
}
echo '<pre>';
//print_r($matriz_up);
//print_r($m_vehiculo_distancias);
print_r(sortArray($matriz_up, $m_vehiculo_distancias)); //this is result
Working fiddle: CLICK!

Categories