Multidimensional array loop php - php

New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.

You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.

Related

Make PHP Array From Dynamic Number of Columns Queried

I have a query which converts item rows of a series of IDs in MySQL table to columns, so the result has variable number of columns (VC). The only items that are not dynamic are the ID, FirstName, LastName. I know the number of variable items (n), which is part of the query.
what I want to do is to have a loop inside PHP while to add these variable columns to the PHP array.
something like this:
$someArray = [];
while($row = $result -> fetch_assoc()) {
array_push($someArray,[
'ID' => $row['EmployeeID'],
'FName' => $row['FName'],
'MName' => $row['MName'],
'LName' => $row['LName'],
-------Loop here --------
'VC1' => $row['VC1'],
'VC2' => $row['VC2'],
'VC3' => $row['VC3'],
'VC4' => $row['VC4'],
'VC5' => $row['VC5'],
..............
'VCn' => $row['VCn']
-------------------------
]);
}
I tried with PHP loop and could not figure out how to do it.
Thanks for any help in advance.
If you know n you can use for loop:
for($i = 1;$i <= $n; $i++) {
$key = "VC" .$i;
$someArray[$key] = $row[$key];
}
However, if you pushing the entire array in it may be better do modify your SQL query and do just:
while($row = $result -> fetch_assoc())
array_push($someArray, $row)

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

PHP array_search with associative array

I've an array's
first one:
[0] => 0289 [1] => 0146 [2] => 5519 [3] => 5308 [4] => 5503 [5] => 5357
second one(associative):
[78941] => 5308 [15749] => 5519 [1469156] => 5308 [78971413] => 5357 [418979] => 0289
Need to find keys in second one by first one value. One by one. I did some loop:
for($i=0;$i<=5;$i++){
$keys=array_search($first_array[$i],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
}
But get nothing. What I'am doing wrong?
Addition
The second array is more large than I show here, approximately 10000 values.
I must insert 5 values per file and these values must be uniq, to avoid overlap.
It will be looks like :
$t=0;
for($i=0;$i<=count($second_array);$i++){
$keys=array_search($first_array[$t],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
$t++
if ($t==5){$t=0}
}
Hope it would help.
If you need only keys, so just filter them:
$keys = array_intersect($first, array_keys($second));
However, if you want to get both values and keys, then it'll be like:
$keysAndValues = array_intersect_key($second, array_flip($first));
You can do it much simple way using foreach loop
<?php
$i = 0;
foreach($array2 as $key => $value):
if($array1[$i] == $value) {
//$key is the required key, manage your stuffs here.
}
$i++;
endforeach;
?>
foreach($first_array as $first_key => $first_value){
foreach($second_array as $second_key => $second_value){
if($first_value == $second_value){
file_put_contents($file_name, $second_key . "\n", FILE_APPEND);
}
}
}
array_search() returns the key if it finds the value, and returns false if not found, so if
you want keys, this code is what you want:
$one=array("0"=>"0146","1"=>"5519","2"=>"5308","3"=>"5503","4"=>"5357");
$two=array("78941"=>"5308","15749"=>"5519","1469156"=>"5308","78971413"=>"5357","418979"=>"5357");
$result=array();
for($i=0;$i<=5;$i++){
if(array_search($one[$i],$two))
$result[]=array_search($one[$i],$two);
}
print_r($result);//OR file_put_contents('check.txt',$result,FILE_APPEND)

How to merge my arrays for DB insertion?

I have 2 associative arrays.
Array ( [title1] => test1 [title2] => test2 [title3] => test3 )
and
Array ( [image1] => images1.jpeg [image2] => images2.jpg [image3] => images3.png )
I want to insert each title and image name into database columns(image title and image name).
How it is possible? Anyway to merge them and after that do insertion?
$finalArray = array();
// Use min to avoid improper "OutOfBounds"
$lengthOfArray = min(count($array1), count($array2));
for(i = 1; i <= $lengthOfArray; $i++) {
array_push($finalArray,
array(
'title' => $array1['title' + $i],
'image' => $array2['image' + $i]
)
);
}
With this, in your finalArray you will have tuples of title an image for every database entry.
Look at array_combine()
Maybe instead of combining the arrays, you can use a foreach to construct your query from the two arrays:
//ARRAYS
$a1=array('title1' => 'test1','title2' => 'test2','title3' => 'test3',);
$a2=array('image1' => 'images1.jpeg', 'image2' => 'images2.jpg', 'image3' => 'images3.png');
$fos=''; //we will collect values into this string
foreach ($a1 as $k=>$v) { //we iterate through the first array
$k2=substr($k, 5); //we get the number from the array key (like 2 from title2)
$fos.=empty($fos) ? '' : ', '; //adding commas when needed
$fos.="('{$v}', '{$a2['image'.$k2]}')"; //adding the right values to the values string
}
$q="insert into images (title, filename) values $fos"; //and finishing up the query
In this case the constructed query will be like:
insert into images (title, filename) values
('test1', 'images1.jpeg'),
('test2', 'images2.jpg'),
('test3', 'images3.png')
Note: of course array values need to be correctly escaped for DB usage
array_merge($array1, $array2);

getting each value of an associative array

i need help building a function that display an associative array and i want to insert them in a variable. for example i have this assoc array :
$array[ID] = 1;
$array[Name] = John;
$array[age] = 12;
$array[ID]=2;
$array[Name] = Mary;
$array[age] = 14;
i need to make the ID,name,age as variables so i can display it in a table. when i loop through them each time it fills the table row. it has to be each one a variable coz i need to insert them into a gird and display the grid .. where then i can update delete the info
I'd use one of the answers provided but if you really really want to (again, i don't see a reason but what the hell do i know) use extract()
<?php
$people = array(
array('id' => 1, 'name' => 'John', 'age' => 12),
array('id' => 2, 'name' => 'Mary', 'age' => 14)
);
foreach($people as $row) {
extract($row);
echo "Id: $id, Name: $name, Age: $age\n";
}
//Prints:
//Id: 1, Name: John, Age: 12
//Id: 2, Name: Mary, Age: 14
~
Currently it looks as if you are overwriting the values of the first person with the values of the second person.
What you're looking for is an array structure with more than one dimension, like this:
$people = array(
1 => array('name' => 'John', 'age' => 12),
2 => array('name' => 'Mary', 'age' => 14)
);
Then it'll be easy to print out table rows:
foreach($people as $id => $person){
print '<tr><td>'.$id.'</td><td>'.$person['name'].'</td><td>'.$person['age'].'</td></tr>';
}//foreach
Hope this helps!
foreach($array as $row) {
echo $row['ID'],$row['Name'],$row['age'];
}
Im not sure what you want to do exactly, but maybe it is the extract function you are looking for.
foreach($array as $key => $value){
echo $key. ' = '.$value.";
}
would give you
ID = 1
Name = John
age = 12
etc
Also be sure to do $array["ID"] = ... instead of $array[ID] = ...
You can do:
foreach($array as $user) {
list($age, $name, $id) = array_values($user);
echo $id, $name, $age;
}
But like others already pointed out, this is pointless because you can much more easily read the values directly from the array through their associative keys. You also wouldnt have to run array_values to assign the array values before being able to assign them with list.

Categories