Arrays and nested foreach - php

I have two array output (using preg_match_all), for example: $name[1] and $family[1].
i need to put these arrays together, and i use foreach as this:
foreach( $name[1] as $name) {
foreach( $family[1] as $family) {
echo $name.$family.'<br />';
}
}
but it don't work.
(each foreach loop works separately)

Assuming they have matching keys for the loop:
foreach( $name as $key => $value) {
echo $value[$key] . $family[$key] . '<br />';
}
This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1].
If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.

$together= array();
foreach( $name as $key => $n) {
$tuple= array('name'=>$name[$key],'family'=>$family[$key]);
$together[$key]= $tuple;
}
foreach( $together as $key => $tuple) {
echo "{$tuple['name']} {$tuple['family']}<br />";
}

Use array_combine():
Creates an array by using the values from the keys array as keys and
the values from the values array as the corresponding values.
PHP CODE:
$nameFamilly=array_combine($name[1] , $family[1]);
foreach( $nameFamilly as $name=>$familly) {
echo $name.$family.'<br />';
}

Related

Getting formatted result with nested arrays in PHP

I am trying to generate sql statement dynamically with loops but i am not getting any idea on how to do it with html name array.
assuming $name and $message are post arrays ... and assuming length of both will be equal,
following is a method i tried;
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($values as $key){
foreach ($key as $value){
echo $value.",";
}
}
?>
output is =
name1,name2,message1,message2,
but i want output as =
(name1,message1),(name2,message2),
Edit : I have acess to $values only and I will not be able to determine how many values are going to join in $values ..
like it can be
$values=array($name,$message,$phone);
and the result i want will be
(name1,message1,phone1),(name2,message2,phone2)
My solutions is
Step 1: Loop your $values this will gonna loop every index of your array like $name
foreach($name as $index => $value) {
// do something
}
Step 2: Inside your loop values start with ( which mean wrap your detail in (
echo "(";
Step 3: loop parent array
foreach($values as $key => $arr) {
// do something
}
Step 4: Inside the loop of your parent array display each data according to your index
echo $values[$key][$index];
$key represents the index of your parent array while $index represents the index of your child array like $name
this loop will create data like
(name1,message1,phone1)
and I just add this
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
to avoid adding , after the last loop
This code will dynamically display array you put inside $values
So your code would be like this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$married= array('yes','no','yes','yes' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
echo "(";
foreach($values as $key => $arr) {
echo $values[$key][$index];
if ($key < sizeof(array_keys($values))-1) {
echo ",";
}
}
echo "),";
}
Demo
or this
$name = array('name1','name2','name3','name4' );
$mess= array('message1','message2','message3','message4' );
$phone= array('phone1','phone2','phone3','phone4' );
$values = array($name,$mess,$phone);
foreach($name as $index => $value) {
$join = array();
foreach($values as $key => $arr) {
$join[] = $values[$key][$index];
}
echo "(".implode(",",$join)."),";
}
Demo
$name = array('name1','name2' );
$mess = array('message1','message2' );
foreach ($names as $k => $v){
echo "(".$v.",".$mess[$k]."),";
}
Try this, you not need two foreach loop, only use foreach loop and pass key to other array and get value
$name = array('name1','name2' );
$mess= array('message1','message2' );
$values = array($name,$mess);
foreach ($name as $keys => $vals)
{
echo "(".$vals.",".$mess[$keys]."),";
}
DEMO
You can use arrap_map() function in order to join two array. Here is reference http://php.net/manual/en/function.array-map.php
<?php
$name = array('name1','name2' );
$mess= array('message1','message2' );
$value = array_map(null, $name, $mess);
print_r($value);
?>

exploade accosiative array type data

I have data like following
string(133) "lindsey#testmail.com=>5.jpg,rickey#testmail.com=>6.jpg,darnell#testmail.com=>84.jpg,ball#gmail.com =>49.jpg,norton#tesing.com=>68.jpg"
i want to explode email and image separately.
i use explode but it didn't work.
i also try associative array.
here is my code but it didn't work.
foreach ($array as $key => $value ) {
echo $key;
echo "<li><img src=\"".base_url()."images/menters/".$values."\" class=\"img-border\"/><span>icon</span></li>\n";
}
i think it happen additional string(133)
i have no idea how to accomplish this
You can't do that with a single explode, you have to explode the string twice. You can then use an associative array to store values and use them
$array = explode(',' $string);
foreach ($array as $key => $val) {
$exp = explode('=>', $val);
$assoc_array[$key]['mail'] = $exp[0];
$assoc_array[$key]['img'] = $exp[1];
}
foreach ($assoc_array as $val) {
echo 'Mail : ', $val['mail'], '<br>';
echo 'Image : ', $val['img'];
}

PHP Nested loops where values are the key to the next level of the array

I'm relatively new to PHP and I hope you can help me solve my problem. I am selecting out data from a database into an array for timekeeping. Ultimately, I would like to calculate the total number of hours spent on a project for a given customer.
Here is the code to populate a multi-dimensional array:
...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
I would now like to iterate over $mArray to generate an xml file like this:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
This nested foreach doesn't work. Can someone give me a couple of tips on how to traverse this structure? Thank you for reading!
UPDATE:
Based on the comments I've received so far (and THANK YOU TO ALL), I have:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
This is now only providing a single iteration (one row of data).
Foreach syntax is foreach($array as $value). You're trying to use those values as array keys, but they're not values - they're the child arrays. What you want is either:
foreach($mArray as $username) {
foreach($username as ...)
or
foreach($mArray as $key => $user) {
foreach($mArray[$key] as ...)

Retrieving array keys from JSON input

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

get all values from php associative array

I have an array $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);. How can i get (echo) all names and corresponding ages in a single instance (like foreach $value as $value)?? The array may have more data than shown here.
foreach ($ages as $name => $age) {
echo "$name = $age\n";
}
u have a lot options
like
print_r
print_r($array)
var_dump , foreach
print_r($array);
or
var_dump($array)
foreach ($ages as $key => $value) {
echo $key . "'s age is " . $value . "<br />";
}

Categories