I'm trying to concatenate an array, but when PHP comes across an empty array-item, it stops concatenating.
My array looks like this:
Array
(
[0] => Array
(
[0] => Test1
[1] => Test1
[2] =>
)
[1] => Array
(
[0] => Test2
[1] => Test2
[2] =>
)
[2] => Array
(
[0] => Test3
[1] => Test3
[2] => Test3
)
)
The 3th item on the first 2 Array-items are empty. And when I loop over them like this:
$keys = array('uid', 'type', 'some_column', 'other_column');
foreach ($csv as $i => $row) {
$uid = $row[0] . $row[1] . $row[2];
array_unshift($row, $uid);
$csv[$i] = array_combine($keys, $row);
}
I only get Test3Test3Test3 back, instead of the expected
Test1Test1
Test2Test2
Test3Test3Test3
So it looks like PHP is skipping items when concatenating an empty value.
Is this normal PHP behavior? And if so, how can I tackle this?
Try like
$uid = array();
foreach ($array as $i => $row) {
$uid[] = $row[0] . $row[1] . $row[2];
}
var_dump($uid);
Just you are giving $uid and it is taking it as an type variable and it appends the last occurance of loop into that variable.If you want your desired output you need to declare it as an array before.
I'm sorry, but if that is your desired output, you're overcomplicating things:
$foo = array(
array("Test1","Test1"),
array("Test2","Test2"),
array("Test3","Test3","Test3")
);
echo implode(PHP_EOL,
//implode all child arrays, by mapping, passes no delimiter
//behaves as concatenation
array_map('implode',$foo)
);
Returns:
Test1Test1
Test2Test2
Test3Test3Test3
In your case, you can use bits of this code like so:
$csv = array(array("Test1","Test1",''),array("Test2","Test2",''),array("Test3","Test3","Test3"));
$keys = array('uid', 'type', 'some_column', 'other_column');
foreach($csv as $k => $row)
{
array_unshift($row,implode('',$row));
$csv[$k] = array_combine($keys,$row);
}
gives:
Array
(
[0] => Array
(
[uid] => Test1Test1
[type] => Test1
[some_column] => Test1
[other_column] =>
)
[1] => Array
(
[uid] => Test2Test2
[type] => Test2
[some_column] => Test2
[other_column] =>
)
[2] => Array
(
[uid] => Test3Test3Test3
[type] => Test3
[some_column] => Test3
[other_column] => Test3
)
)
Try this:
$uid = array();
foreach ($array as $i => $row) {
$uid[] = $row[0] . $row[1] . $row[2];
}
var_dump($uid);
This outputs:
Array
(
[0] => Test1Test1
[1] => Test2Test2
[2] => Test3Test3Test3
)
You can do something similar to produce a string:
$uid = '';
foreach ($arr as $i => $row) {
$uid .= $row[0] . $row[1] . $row[2] . "\n";
}
echo $uid;
Output:
Test1Test1
Test2Test2
Test3Test3Test3
To get the expected output
$uid = "";
foreach ($array as $i => $row) {
$uid .= $row[0] . $row[1] . $row[2] . "\n";
}
echo $uid;
You need to use two foreach loop..
Procedure:
Initialize your first foreach loop to get the key => value as $key=> $value of each array inside.
Then initialize your second loop to $value variable since value inside of this is another array key => value = $innerKey => $innerValue.
Then inside your second loop echo $innerValue to display values inside of the secondary array
Lastly put an echo '<br/>' inside your first loop to put each secondary array into another newline.`
.
$data = array(
0 => array(
0 => 'Test1',
1 => 'Test1',
2 => ''
),
1 => array(
0 => 'Test2',
1 => 'Test2',
2 => ''
),
2 => array(
0 => 'Test3',
1 => 'Test3',
2 => 'Test3'
)
);
foreach($data as $key => $value){
foreach($value as $innerKey => $innerValue){
echo $innerValue;
}
echo '<br/>';
}
// Output would be..
Test1Test1
Test2Test2
Test3Test3Test3
Code Tested at : PHP Fiddle
Related
sorry if the questions seams stupid but I have created an array in my controller and I pass it to the view with the $data[] array.
And I don't get it right to print the array with a for loop.
Can you please help me?
$measurearray = array(
'nr' => $answerNr,
'responsible' => $responsible,
'creationdate' => $InvDate2,
'activity' => $reason
);
$arr[$i] = $measurearray;
$data["failedMeasures_nr"] = $arr;
Output :
Array (
[50] => Array (
[0] => Array (
[nr] => 5d
[responsible] => werner
[creationdate] => asdfgdf
[activity] => appointed.
)
)
[73] => Array (
[0] => Array (
[nr] => 9g
[responsible] => 42887
[creationdate] => Zuzana
[activity] => r the training.
)
)
)
This is what happens when I print_r() it in the view.
My target is to print every single element for itself!
Have you tried this?
foreach ( $failedMeasures_nr[0] as $key => $val ) {
echo $key . ' is ' . $val;
}
With a foreach you can print separately the array elements
Please note that if you want to print more than the first index ( the 0 in my example ) you should use another foreach, resulting in something like this:
foreach ( $failedMeasures_nr as $new_arr ) {
foreach ( $new_arr as $key => $val ) {
echo $key . ' is ' . $val;
}
}
this way you will print the whole array separately
You can use foreach method to print each value.
<?php
foreach ($failedMeasures_nr as $print):
echo $print['nr'];
echo $print['responsible'];
echo $print['creationdate'];
echo $print['activity'];
endforeach;
?>
// controller page try this,
$data[$i]["failedMeasures_nr"] =array('nr' => $answerNr,
'responsible' => $responsible,
'creationdate' => $InvDate2,
'activity' => $reason);
$this->load->view('view_page',$data);
In View Page try this code,
for($i =0 ; $i <count($data);$i++){
foreach ($data[$i] as $key => $value) {
echo "$value";
echo "<br>";
}
}
My arrays are
$name=>
Array
(
[0] => General
[1] => General
[2] => Outdoors
[3] => Dining
[4] => Dining
[5] => Kitchen
[6] => Kitchen
)
$key1=>
Array
(
[0] => 1
[1] => 2
[2] => 7
[3] => 11
[4] => 12
[5] => 17
[6] => 18
)
Array function
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
Here I would like to print the values by using the same keys
if $name having the index as [0] and my $key1 also take the [0] value
i.e: my result should be in the form of
General => 1
General => 2
Outdoors => 7
Dining => 11
Dining => 12
Kitchen => 17
Kitchen => 18
You only need to iterate one array, not both of them:
foreach ($name as $key => $name_value) {
echo "$name_value => " . $key1[$key];
}
You can use a simple for loop to do this
for ($i = 0; $i < count($name); $i++) {
echo $name[$i] . '=>' . $key[$i]
}
The problem with your code is you're using the same variable $key for both foreachs, so the last one overwrites the value.
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
You could make things easier by combining those two arrays, making $name array be the keys and $key1 array be the values
$newArray = array_combine($name, $key1);
foreach ($newArray as $name => $key) {
echo "{$name} =>{$key}";
}
This will work for you
<?php
$a1= array('General','Outdoors','Dining ');
$a2= array('1','2','3');
$newArr=array();
foreach($a1 as $key=> $val)
{
$newArr[$a2[$key]]= $val;
}
echo "<pre>"; print_r($newArr);
?>
output
Array
(
[1] => General
[2] => Outdoors
[3] => Dining
)
I am afraid this wont be possible if you want the output as associative array as same key name in an associative array is not allowed. It would be always overwritten if you are dealing with the associative arrays.
Although you may have something like this:
array_map(function($key, $val) {return array($key=>$val);}, $name, $key1)
Output:
Array ( [0] => Array ( [General] => 1 ) [1] => Array ( [General] => 2 ) [2] => Array ( [Outdoors] => 7 ) [3] => Array ( [Dining] => 11 ) [4] => Array ( [Dining] => 12 ) [5] => Array ( [Kitchen] => 17 ) [6] => Array ( [Kitchen] => 18 ) ).
But if you want the output in string format It is possible.
for ($i = 0; $i < count($key); $i++) {
echo $name[$i] . '=>' . $key[$i].'<br>';
}
Just change the foreach as follows...
foreach ($key1 as $key => $value1) {
echo $name[$key] ."=>". $value1."<br>";
}
replace the <br> with \n if you're running through the linux terminal. Also don't miss the '.' operator to concatenate the string..
Nested foreach won't do what you need... Good luck..
I am fetch facebook user's working history, and when I print_r, I get an array like this:
Array (
[work] => Array (
[0] => Array (
[employer] => Array (
[id] => 111178415566505
[name] => Liputan 6 SCTV
)
) [1] => Array (
[employer] => Array (
[id] => 107900732566334
[name] => SCTV
)
)
)
[id] => 502163984
)
How do I display only the value from name, so the output will be like this:
Liputan 6 SCTV
SCTV
I used foreach, but always an error always happens.
Try this:
foreach ($array['work'] as $arr) {
echo $arr['employer']['name']."<br>\n";
}
This is assuming your data looks like:
$array = array(
'work' => array(
array(
'employer' => array('id' => 111178415566505, 'name' => 'Liputan 6 SCTV'),
),
array(
'employer' => array('id' => 107900732566334, 'name' => 'SCTV'),
),
),
'id' => 502163984,
);
for instance your array variable name is $test, then you can get name value by
$test['work'][0]['employer']['name']
you can check your array structure using pre tag, like
echo '<pre>';print_r($test);
You can use array_reduce, implode, and closure (PHP 5.3+) to do this.
echo implode("<br/>", array_reduce($array["work"],
function(&$arr, $v){
$arr[] = $v["employer"]["name"];
},array()
));
I assume $arr is working history array. You can use for Then array look like this :
for($i=0, $records = count( $arr['work']); $i < $records; $i++) {
echo $arr['work'][$i]['employer']['name'] ."<br>";
}
Using foreach
foreach( $arr['work'] as $works) {
echo $works['employer']['name'] ."<br>";
}
foreach ($your_array as $your_array_item)
{
echo $your_array_item['work'][0]['employer']['name'] . '<br>';
}
$count=count($array);
for($i=0,$i<=$count;$i++){
echo $array['work'][$i]['employer']['name'];
}
This will work.. Dynamically..
foreach ($array['work'] as $val_arr) {
echo $val_arr['employer']['name']."<br />";
}
There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.
I'm implementing memcached on a site and I'm caching the results of a specific query, which is working great, but I am having problems putting together the code to set the variables I need to make the cache usable.
My array is as follows, which contains two groups of data:
Array ( [0] => Array ( [0] => 9126 [id] => 9126 [1] => Oh penguin, you so silly. [title] => Oh penguin, you so silly. [2] => November-01-2011-00-14-09-ScreenShot20111031at9.jpg [path] => November-01-2011-00-14-09-ScreenShot20111031at9.jpg ) [1] => Array ( [0] => 9131 [id] => 9131 [1] => Reasons you die... [title] => Reasons you die... [2] => November-01-2011-00-17-04-ScreenShot20111031at8.jpg [path] => November-01-2011-00-17-04-ScreenShot20111031at8.jpg ) )
I can set them manually, and call them like this:
$id = $clean[0][0];
$title = $clean[0][1];
$path = $clean[0][2];
But I am having problems writing a WHILE loop to go through and set the variables dynamically. I also tried a FOR EACH statement to no avail:
for each($clean as $image){
$id = $image->id;
$path = $image->path;
$title = $image->title;
echo "THIS IS YOUR FREAKING ID $id THIS IS YOUR TITLE $title THIS IS YOUR PATH $path";
}
Any insight?
Edit:
Solution was to not call them as objects, as pointed out, change to reference them like this:
$id = $image["id"];
$path = $image["path"];
$title = $image["title"];
Cheers.
$array = array(
array ( 0 => 9126,
'id' => 9126,
1 => 'Oh penguin, you so silly.',
'title' => 'Oh penguin, you so silly.',
2 => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg',
'path' => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg' ),
array ( 0 => 9126,
'id' => 9126,
1 => 'Oh penguin, you so silly.',
'title' => 'Oh penguin, you so silly.',
2 => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg',
'path' => 'November-01-2011-00-14-09-ScreenShot20111031at9.jpg' )
);
foreach( $array as $row)
{
// Based on your array, you can either do:
echo $row['id'] . ' ' . $row['title'] . $row['path']. "\n";
echo $row[0] . ' ' . $row[1] . ' ' . $row[ 2 ] . "\n";
}
You could just serialize the entire array before saving in cache, then unserialize when you retrieve from cache. Then just reference the values as you indicated.
For each should serve you well. If you need to iterate through $clean as well just wrap around another foreach.
$arr = $clean[0];
foreach ($arr as $value) {
echo $value; // or in your case set
}