Pushing two values from the database to one array - php
On line 6 I am pushing a value from the database to the array called $products. I would now like to give another value from the database ($row->image) to the same array which matches with $row->name.
Maybe it could make sense to use a two dimensional array but I don't know how to do this in this case.
$products = array();
foreach($_POST['selected_checkboxes'] as $value) {
if($result = $db->query("SELECT * FROM produkte WHERE $value = 1")){
while($row = $result->fetch_object()) {
if (!in_array($row->name, $products)) {
array_push($products, $row->name);
}
}
}
else {
array_push($products, 'error');
}
}
The result should show me the name and the image of both values which belong together.
You could do this, assuming you already have your $row->name and $row->image matching logic sorted:
if (!in_array($row->name, $products)) {
array_push( $products, array('name'=>$row->name, 'image'=>$row->image) );
}
You can try it like this:
$products = array();
foreach ( $_POST['selected_checkboxes'] as $value ) {
if ( $result = $db->query( "SELECT * FROM produkte WHERE $value = 1" ) ) {
while ( $row = $result->fetch_object() ) {
// if your name is unique you can do it like this,
// if not just take $row->id as index
if( isset( $products[$row->name] ) ) continue;
$products[$row->name] = array( "name" => $row->name, "image" => $row->image );
}
} else {
array_push( $products, 'error' );
}
}
// if you want to have plain digits as index you can get a reindexed array
$products = array_values( $products );
then you will get an array like that:
array(//$products
array(
"name" => "productname",
"image" => "productimage"
)
);
I think you can achieve that if you use a stdClass object.
$std = new stdClass();
$std->name = $row->name;
$std->image = $row->image;
array_push($products, $std);
Or you can change your sql query to
SELECT name, image FROM produkte WHERE $value = 1
and
array_push($products, $row);
Related
How to extract data from JSON - Laravel & JSON
This is how my json looks like ["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}]. Is there a way that i can get the data out the results like Chicken : 1, Froggies:2, Fryies:3 I tried to use implode to get this done but i get an error saying array to string conversion, Below is my code foreach($request->get('item_id') as $key => $id) { $selected_item = Item::all()->where('id',$id); foreach($selected_food as $select) { $food_selected[]= $select->name ; $food_selected[] = ['quantity' => $request->get('quantity')[$key]]; } } $query ="Your items are ".implode(',',$food_selected)."";
Maybe array of objects would be more useful in that situation, which you could get this way: $arr = []; foreach ( $request->get('item_id') as $key => $id ) { $selected_item = Item::all()->where('id', $id); foreach ( $selected_item as $select ) {// $selected_item or $selected_food here /* $obj = new stdClass; $obj->{$select->name} = $request->get('quantity')[$key]; $arr[] = $obj;*/ $arr[$select->name] = (int) $request->get('quantity')[$key]; } } $query = ''; foreach ( $arr as $k => $v ) { $query .= ' '.$k.': '.$v.','; } $query = rtrim($query, ','); $query = ltrim($query); $query = "Your items are ".$query;
I assume that the ID is unique key for an Item and your Item::all()->where('id',$id) will return only one record. If this is true, the second loop is unnecessary. Based on this assumption, I come to this code: $result = collect($request->get('item_id')) ->map(function($itemId, $itemKey) use ($request) { $item = Item::find($itemId); return $item->name . ' : ' . $request->get('quantity')[$itemKey]; })->implode(','); // $result contains the string: "Chicken : 2, Fries : 1" For explanation: Cast the array into a collection Use map to loop over it Find the Item by its ID Return the name and the quantity (this returns a collection) Implode the collection
How to convert few columns as JSON array in php while csv import
i have a csv file, please see this below image of my CSV and this is my table i need a help to split few columns and convert as an array and insert in to table, lets say i want to exclude the first column which is 'product_id' from the array and remaining all columns as array and insert in to table, so the expected query will be like insert into process_detail (product_id,product_attributes) values ($product_id,'[{"color":"blue","style":"classic","material_type":"etc","length":"35 cm","price":"11.25","product_description":"etc"}]'; note: my csv headers which are in the first row in CSV file will match exactly with Mysql table headers this is my php function convert($string) { return htmlspecialchars($string,ENT_QUOTES); } $columnArray = array(); $dataArray = array(); $firstRule = true; while ($data = fgetcsv ($source, 1000, ",")) { if($firstRule) { foreach($data as $columnName) { $columnArray[] = $columnName; } $firstRule = false; } else { $rule = array(); for($i = 0; $i < count($data) ; $i++) { $rule[$columnArray[$i]] = $data[$i]; } $dataArray[] = $rule; } } foreach($dataArray as $data) { // here i am stuck, i would want to json_encode of few columns and insert into table } echo $product_id; var_dump($bound_values); mlarray(2) { ["product_id"]=> string(2) "ml" ["product_attributes"]=> string(1588) "{"cv_id":"weight_2_kg","sv_id":"label_3","collection_id":"length_3_cm","season":"width_3_cm","hit":"height_3_cm","tier":"diameter_3_cm","style_no":"size_3_ml","base_product_id":"weight_3_kg","product_title":"label_4","introduction":"length_4_cm","color_name":"width_4_cm","price_a":"height_4_cm","color_price_a":"diameter_4_cm","sku_price_a":"size_4_ml","price_b":"weight_4_kg","color_price_b":"label_5","price_c":"length_5_cm","color_price_c":"width_5_cm","sku_price_c":"height_5_cm","product_availability_b":"diameter_5_cm","product_availability_c":"size_5_ml","product_availability_d":"weight_5_kg","returnable_a":"label_6","returnable_b":"length_6_cm","returnable_c":"width_6_cm","collect_a":"height_6_cm","collect_b":"diameter_6_cm","collect_c":"size_6_ml","brand":"weight_6_kg","group_name":"label_7","department":"length_7_cm","class_name":"width_7_cm","sub_class":"height_7_cm","category_1":"diameter_7_cm","category_2":"size_7_ml","category_3":"weight_7_kg","category_4":"label_8","category_5":"length_8_cm","copy_writing_agency":"width_8_cm","photographer_name":"height_8_cm","photography_date":"diameter_8_cm","event":"size_8_ml","status":"weight_8_kg","style":"label_9","p_family":"length_9_cm","pf_name":"width_9_cm","feature_1":"height_9_cm","primary_material":"diameter_9_cm","secondary_material":"size_9_ml","type_name":"weight_9_kg","material_finish_1":"label_10","material_finish_2":"length_10_cm","for_name":"width_10_cm","gender":"height_10_cm","care_instructions":"diameter_10_cm","fragile":"size_10_ml","assembly_required":"weight_10_kg","unit_components":"segment"}" } 2536789array(2) { ["product_id"]=> string(7) "2536789" ["product_attributes"]=> string(1570) "{"cv_id":"","sv_id":"","collection_id":"","season":"JJ17","hit":"JJ17","tier":"TIER1","style_no":"11DD DV","base_product_id":"","product_title":"something","introduction":"","color_name":"blue","price_a":"169","color_price_a":"","sku_price_a":"","price_b":"189","color_price_b":"","price_c":"1.5","color_price_c":"","sku_price_c":"","product_availability_b":"","product_availability_c":"","product_availability_d":"","returnable_a":"","returnable_b":"","returnable_c":"","collect_a":"","collect_b":"","collect_c":"","brand":"brand a","group_name":"group b","department":"something else","class_name":"something","sub_class":"","category_1":"","category_2":"","category_3":"","category_4":"","category_5":"","copy_writing_agency":"","photographer_name":"","photography_date":"","event":"exclusive","status":"Active","style":"Basic","p_family":"something","pf_name":"something else","feature_1":"","primary_material":"Glass","secondary_material":"Glass","type_name":"something","material_finish_1":"something","material_finish_2":"","for_name":"","gender":"","care_instructions":"","fragile":"Yes","assembly_required":"","unit_components":"","unit_pack_length_cm":"24","unit_pack_width_cm":"16","unit_pack_height_cm":"32","unit_pack_weight_g":"","length_cm":"","width_cm":"","height_cm":"","weight_kg":"","size_ml":"250","diameter_cm":"","set_includes":"","label_1":"","length_1_cm":"","width_1_cm":"","height_1_cm":"","diameter_1_cm":"","size_1_ml":"","weight_1_kg":"","label_2":"","length_2_cm":"","width_2_cm":"","height_2_cm":"","diameter_2_cm":"","size_2_":"","":""}" }INSERT INTO process_detail (process_id,product_id,product_attributes) values(1,'2536789','[{"cv_id":"","sv_id":"","collection_id":"","season":"JJ17","hit":"JJ17","tier":"TIER1","style_no":"11DD DV","base_product_id":"","product_title":"something","introduction":"","color_name":"blue","price_a":"169","color_price_a":"","sku_price_a":"","price_b":"189","color_price_b":"","price_c":"1.5","color_price_c":"","sku_price_c":"","product_availability_b":"","product_availability_c":"","product_availability_d":"","returnable_a":"","returnable_b":"","returnable_c":"","collect_a":"","collect_b":"","collect_c":"","brand":"brand a","group_name":"group b","department":"something else","class_name":"something","sub_class":"","category_1":"","category_2":"","category_3":"","category_4":"","category_5":"","copy_writing_agency":"","photographer_name":"","photography_date":"","event":"exclusive","status":"Active","style":"Basic","p_family":"something","pf_name":"something else","feature_1":"","primary_material":"Glass","secondary_material":"Glass","type_name":"something","material_finish_1":"something","material_finish_2":"","for_name":"","gender":"","care_instructions":"","fragile":"Yes","assembly_required":"","unit_components":"","unit_pack_length_cm":"24","unit_pack_width_cm":"16","unit_pack_height_cm":"32","unit_pack_weight_g":"","length_cm":"","width_cm":"","height_cm":"","weight_kg":"","size_ml":"250","diameter_cm":"","set_includes":"","label_1":"","length_1_cm":"","width_1_cm":"","height_1_cm":"","diameter_1_cm":"","size_1_ml":"","weight_1_kg":"","label_2":"","length_2_cm":"","width_2_cm":"","height_2_cm":"","diameter_2_cm":"","size_2_":"","":""}]') this is my csv content product_id,cv_id,sv_id,collection_id,season,hit,tier,style_no,base_product_id,product_title,introduction,color_name,price_a,color_price_a,sku_price_a,price_b,color_price_b,price_c,color_price_c,sku_price_c,product_availability_b,product_availability_c,product_availability_d,returnable_a,returnable_b,returnable_c,collect_a,collect_b,collect_c,brand,group_name,department,class_name,sub_class,category_1,category_2,category_3,category_4,category_5,copy_writing_agency,photographer_name,photography_date,event,status,style,p_family,pf_name,feature_1,primary_material,secondary_material,type_name,material_finish_1,material_finish_2,for_name,gender,care_instructions,fragile,assembly_required,unit_components,unit_pack_length_cm,unit_pack_width_cm,unit_pack_height_cm,unit_pack_weight_g,length_cm,width_cm,height_cm,weight_kg,size_ml,diameter_cm,set_includes,label_1,length_1_cm,width_1_cm,height_1_cm,diameter_1_cm,size_1_ml,weight_1_kg,label_2,length_2_cm,width_2_cm,height_2_cm,diameter_2_cm,size_2_ml,weight_2_kg,label_3,length_3_cm,width_3_cm,height_3_cm,diameter_3_cm,size_3_ml,weight_3_kg,label_4,length_4_cm,width_4_cm,height_4_cm,diameter_4_cm,size_4_ml,weight_4_kg,label_5,length_5_cm,width_5_cm,height_5_cm,diameter_5_cm,size_5_ml,weight_5_kg,label_6,length_6_cm,width_6_cm,height_6_cm,diameter_6_cm,size_6_ml,weight_6_kg,label_7,length_7_cm,width_7_cm,height_7_cm,diameter_7_cm,size_7_ml,weight_7_kg,label_8,length_8_cm,width_8_cm,height_8_cm,diameter_8_cm,size_8_ml,weight_8_kg,label_9,length_9_cm,width_9_cm,height_9_cm,diameter_9_cm,size_9_ml,weight_9_kg,label_10,length_10_cm,width_10_cm,height_10_cm,diameter_10_cm,size_10_ml,weight_10_kg,segment 2536789,,,,JJ17,JJ17,TIER1,11DD DV,,something,,blue,169,,,189,,1.5,,,,,,,,,,,,brand a,group b,something else,something,,,,,,,,,,exclusive,Active,Basic,something,something else,,Glass,Glass,something,something,,,,,Yes,,,24,16,32,,,,,,250,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, thanks in advance.
There are a handful of ways to approach this problem, however this is the way that I would solve it. Note that this is untested code, so please either troubleshoot or else ask in comments if there's some issue / error. NOTE: the size limit in the fgetcsv is optional, and not necessary, and in this case, causing problems - so remove the limit per the code below. I've commented the code below to tell you what's going on at each step: // declare an empty array to contain the column keys $keys = []; // load the keys into the $keys array // load the first row $data = fgetcsv( $source ); // loop over it, adding the keys into the array foreach( $data AS $value ) { if ( $value ) { $keys[] = $value; } } /** * $keys should now be an array that looks like so: * * $keys = array( * 0 => 'product_id', * 1 => 'color', * 2 => 'style', * 3 => 'type', * ..etc * ); */ // now process the rest of the csv file while ($data = fgetcsv ( $source ) ) { // reset the attributes array, where we'll store the (future) JSON attributes $attributes = []; // reset product_id to ensure pick up the new / correct value $product_id = NULL; // loop over the columns in the row foreach( $data as $index => $value ) { // set the key (based on the keys array established above) $key = $keys[ $index ]; // load the values into the attributes array (unless product id, where we put that in the $product_id variable) if ( 'product_id' != $key ) { $attributes[ $key ] = $value; } else { $product_id = $value; } } if ( empty( $attributes ) || ! $product_id ) { continue; } // prepare the values for a PDO database insert $bound_values = [ 'product_id' => $product_id, 'product_attributes' => json_encode( $attributes ) ]; // insert into the database $stmt = $db->prepare( "INSERT INTO product_table SET product_id = :product_id, product_attributes = :product_attributes" ); $stmt->execute( $bound_values ); }
How can i get Array values to separate php variables
I am trying to retrieve records in MySQL DB.I want to retrieve all the records belong to the img_path column.from the following code I am getting results as an array.but iw ant them as separate variables. My code $result_list = array(); while($row = mysqli_fetch_array($query)) { $result_list[] = $row; } foreach($result_list as $row) { $productitems[] = array( 'img_path' => $row['img_path'], ); } print_r($productitems); Current Output Array ( [0] => Array ( [img_path] => img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png ) [1] => Array ( [img_path] => img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg ) [2] => Array ( [img_path] => img ) ) expected output $variable1 = img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png; $variable2 = img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg;
You can use extract function like this: $result_list = array(); while($row = mysqli_fetch_array($query)) { $result_list[] = $row; } foreach($result_list as $row) { $productitems[] = $row['img_path']; } extract($productitems, EXTR_PREFIX_ALL, "variable"); echo $variable_0; echo $variable_1; echo $variable_2;
You can do that : $result_list = array(); while($row = mysqli_fetch_array($query)) { $result_list[] = $row; } foreach($result_list as $k => $row) { $varName = 'var' . $k; $$varName = array( 'img_path' => $row['img_path'], ); } And you will have access to $var0, $var1, and so forth.
You might use, extract() function. Docs here The extract() function imports variables into the local symbol table from an array. This function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table. This function returns the number of variables extracted on success.
Use list(). http://php.net/manual/en/function.list.php From the manual: $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.\n";
You can also use the following code, where you do not need to use an additional function like list() or extract(). It is also a very minimalistic approach. $result_list = array(); while($row = mysqli_fetch_array($query)) { $result_list[] = $row; } foreach($result_list as $key => $row) { ${'img_path_'.$key} = $row['img_path']; } /* Output: ["img_path_0"]=> string(50) "img/8041171eda3a8fddf508bfd0d9a0866e1472441466.png" ["img_path_1"]=> string(50) "img/91882b5f9ffa624a9dc81dfa0ec980861472441077.jpg" ["img_path_2"]=> string(3) "img" */
Create multidimensional array from keys
Is there a way to create dynamicaly multidimensional array? I have stored in database "path" for each field=>value like that: field_name : [slideshow][slide][0][title] field_value : my title field_name : [slideshow][slide][0][desc] field_value : my desc field_name : [slideshow][slide][1][title] field value : my other title field_name : [slideshow][slide][1][desc] field value : my other desc field_name : [slideshow][settings][duration] field value : 300 and now I'm trying to figure out how to make it an array again. Obviously there can be lots of fields and complexity so I wanted to avoid some recursions if possible, cause I'm not sure how it will impact performance. I was playing around with variable variables and trying something like: $array_name = 'arr'; ${$array_name}[slideshow][slide][1][title] = $field->field_value; print_r($arr); but this works only if its literally that, and nothing like this works: ${$array_name}.$field->field_name = $field->field_value; I basically need to store every field as individual row (e.g. for searches in those fields), values can be diffrent types (even serialized arrays), and contain html. Any advice appreciate.
The basic idea is to split up your field_name string and loop over the parts backward to build up the array. Some recursion is used to merge the arrays, though any performance impact should be negligible. Example: // Set up sample data. $field = new stdClass(); $field->field_name = '[slideshow][slide][0][title]'; $field->field_value = 'my title'; $fields[] = $field; $field = new stdClass(); $field->field_name = '[slideshow][slide][0][desc]'; $field->field_value = 'my desc'; $fields[] = $field; $field = new stdClass(); $field->field_name = '[slideshow][slide][1][title]'; $field->field_value = 'my other title'; $fields[] = $field; $field = new stdClass(); $field->field_name = '[slideshow][slide][1][desc]'; $field->field_value = 'my other desc'; $fields[] = $field; $field = new stdClass(); $field->field_name = '[slideshow][settings][duration]'; $field->field_value = '300'; $fields[] = $field; // End sample data. // array_merge_recursive() doesn't do what we want with numeric keys, so use this function merge($base, $array) { foreach ($array as $key => $value) { if (isset($base[$key]) && is_array($base[$key]) && is_array($value)) { $base[$key] = merge($base[$key], $value); } else { $base[$key] = $value; } } return $base; } $result = []; foreach ($fields as $field) { $parts = array_reverse(explode('][', trim($field->field_name, '[]'))); $value = $field->field_value; foreach ($parts as $part) { $value = [$part => $value]; } $result = merge($result, $value); } print_r($result); Output: Array ( [slideshow] => Array ( [slide] => Array ( [0] => Array ( [title] => my title [desc] => my desc ) [1] => Array ( [title] => my other title [desc] => my other desc ) ) [settings] => Array ( [duration] => 300 ) ) )
You could try something like this. $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); <?php echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>"; ?> <?php for ($row = 0; $row < 4; $row++) { echo "<p><b>Row number $row</b></p>"; echo "<ul>"; for ($col = 0; $col < 3; $col++) { echo "<li>".$cars[$row][$col]."</li>"; } echo "</ul>"; } ?>
array to string php
Hy every one I have this problem with an array I start like this... $name = array($_POST['names']); $nameId = array(); $query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')"); while($row = mysql_fetch_assoc($query)){ $nameId[] = array('ids' => $row['id'] ); } which gives me arrays like this.. $name: array('0'=>'name1,name2,name3') $names: array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1')) how can I bring this in an string/form like this.. array('0'=>'61,6,1') The idea is to save the ids to the Database. Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database? many thanks in advance.
Change your assignment to this: $nameId[] = $row['id'];
$name = array(name1,name2,name3); $nameId = array(); $query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')"); while($row = mysql_fetch_assoc($query)){ //below line changed $nameId[] = $row['id'] ; } $string = implode(',',$nameId);
Try this : $array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1')); $result = implode(",",call_user_func_array('array_merge', $array)); Please note : Here all are numeric keys, so change your code to : $nameId[] = array($row['id'] ); , remove key 'ids' from here Output : 61,6,1
Thats what I think $nameId[] = $row['id']; $stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it. function CustomFindJoinArray( $needly, $array ) { $results = array(); foreach ( $array as $key => $value ) { if ( is_array( $value ) ) { $results = array_merge($results, foo( $needly, $value )); } else if ( $key == $needly ) { $results[] = $value; } } return $results; } echo implode( ",", CustomFindJoinArray( "ids", $your_array ) ); where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1')) OR More simple foreach ($your_array as $key => $ids) { $newArray[] = $array[$key]["ids"]; } $string = implode(',', $newArray);
$ids = array(); foreach($nameId as $curr) { $ids[] = $curr['ids']; } $str = "(".implode(",",$ids).")";