Copy values into another array - php

I have the following code:
foreach ($row as $item) {
foreach($item as $key) {
echo "<pre>";
print_r($key);
echo "</pre>";
}
}
I am trying to copy the keys ($key) into another array for further processing. How can i do this?

define some variable as array $array = array(); and just push the keys in with array_push($array, $key);
$array = array();
foreach ($row as $item) {
foreach($item as $key) {
array_push($array, $key);
}
}

$aNew = array();
foreach($row as $item) {
foreach($item as $key) {
$aNew[] = $key;
}
}
But; why would you do this? You can also just perform your commands / processing inside the second foreach().

If you want to get all keys of an array you may use
array_keys()
instead. Also, if each of your rows has the same keys in your second foreach loop, you may break both of the loops after getting all the keys from the first row.

Just use array_keys()
$a = array();
$array_of_keys = array_keys( $a );

Related

How to remove duplicate value in loop not using array

I want to remove or hide duplicate values in loop , It's not array.
You can see in picture 1/3, & 2/2 is repeating so I want only once using loop. It's not return any array it's simple data so we can't use array_unique
$i=1;
$result = array();
foreach ($boxes as $key => $value) {
foreach ($result as $k => $val) {
echo $i."/".count($value).'</br>';
}
$i++;
}
Expected Output
REG-Pre-Cut Short 1/3
REG-Pre-Cut Long -
PREM-Pre-Cut Short -
PREM-Pre-Cut Short 2/2
PREM-Pre-Cut Long -
Try something like this.
First you create an array in the expected format.
Then use array_unique to remove duplicates.
Then you print out the array.
$i=1;
$result = array();
$outputResult = array();
foreach ($boxes as $key => $value) {
foreach ($result as $k => $val) {
$outputResult[] = $i."/".count($value).'</br>';
}
$i++;
}
$outputResult = array_unique($outputResult);
foreach ($outputResult as $result) {
echo $result;
}

foreach leaves out the very first value

I am processing a foreach(first) which gives the full array in the data, when I make another foreach(second) and pass the first foreach into second foreach the first value of the first foreach never appears in the second foreach. Does anyone have any idea why the foreach behaves this way? is there a solution for this?
I tried it this way no luck
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']);
foreach ($userIdsPerRoom as $value) {
$list[] =$value['UserID'];
}
foreach ($list as $value) {
$userInfo = chatRoomUsersEmail($value);
foreach ($userInfo as $info) {
echo $info['userEmail'];
}
}
echo count($list); ///gives the full list
}
I noticed it with this code
$userIdsPerRoom = chatRoomUsersId($_SESSION['currentRoomID']); //return an array of intergers with five values example array(1,2,3,4,5)
foreach ($userIdsPerRoom as $value){
$userInfo = chatRoomUsersEmail($value['UserID']);
foreach ($userInfo as $info){
echo $info['userEmail']; /// I only get four values example array(b,c,d,e)
}
}

How to "skip" iteration when building a new array using recursion

I am stuck on something that might be very simple.
I am creating a new array by looping through an existing array using a recursion function yet I can not seem to get the values to stick to the new array. The function, in the end, will be a bit more complex, but for now I need some help.
I have tried soooo many ways to get this to work but I am at a loss right now.
Here is my php function
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
As is, the new array never gets filled...BUT, if I change this line...
recursive($value); // Why can't I just call the recursive function here?
...to...
$newArray[] = recursive($value); // Instead of having to set a new value to the new array?
everything works properly...except that my goal was to create a flat array with only the values.
So my question is, why is it necessary to set a new array value in order to call the recursive function again? Ideally, I want to skip setting a new array value if the value is an array and just continue the loop through the original array.
Use array_merge:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or you could use special operator:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
$newArray += recursive($value);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
...or pass a variable by reference like this:
function recursive($array, &$newArray = null) {
if (!$newArray) {
$newArray = array();
}
foreach($array as $key => $value) {
if(is_array($value)){
recursive($value, $newArray);
}else{
$newArray[] = $value;
}
}
return $newArray;
}
use array_merge() to merge the array returned from recursive($value); and $newArray
$newArray = array_merge($newArray,recursive($value));
You can guarantee that $newArray will be flat after this, as the previous value of $newArray was flat, and recursive always returns a flat array, so the combination of both should be a flat array.
You aren't doing anything with the return from your recursive function. Try this:
function recursive($array) {
$newArray = array();
foreach($array as $key => $value) {
if(is_array($value)){
// This is what was modified
$newArray = array_merge($newArray, recursive($value));
}else{
$newArray[] = $value;
}
}
return $newArray;
}

Sorting data from two different sources (PHP)

I need to combine two different data types, an array and an array object.
I then need to display them on a page in order of a certain attribute (date).
The markup for access is similar to the following:
foreach($array as $item){
$item['date'];
}
and
foreach($object as $item){
$item->post->date
}
is array_merge what I need, or something different?
Not that if possible I'd like to do this on the fly, as data will be changing rapidly and there is no need for storage.
Thanks!
Here's how I would do it:
// array we will use for sorting
$finalArray = array();
// add the array's using the date as the key
foreach($array as $item){
$key = $item['date']; // use date here, example $key = date('l \t\h\e jS',$item['date']);
$finalArray[$key] = $item;
}
// add the objects's using the date as the key
foreach($object as $item){
$finalArray[$item->post->date] = $item;
}
//now sort by keys as Xeoncross noted
ksort($finalArray);
foreach($finalArray as $date=>$objOrArray){
if(is_array($objOrArray)){
//do your array printing here
} else {
//do your object printing here
}
}
Ofcourse we can turn the object into an array with get_object_vars, and use whatever sorting function on the final array, the important part is that we want to sort by date and that's why we need it to be our key.
Hope that helped.
foreach($array as $item){
$array_new[] = $item['date'];
}
foreach($object as $item){
$array_new[] = $item->post->date;
}
sort($array_new);
$dates = array();
foreach ($array as $item) {
  $dates[] = $item['date'];
}
foreach ($object as $item) {
$dates[] = $item->post->date;
}
sort($dates);
foreach ($dates as $date) {
echo $date;
}
You could try this if you need multiple values from the objects (not just date) and you don't mind duplicates being erased.
// $array is already defined right?
$object = json_decode(json_encode($object), TRUE);
$data = array_merge($array, $object);
print_r($data); // now test it
http://us2.php.net/array_merge
http://us3.php.net/json_decode (note the second TRUE param)
Edit
Based on Perfection's answer, (and re-reading the question) I would do this:
$finalArray = array();
foreach($array as $item)
{
$finalArray[$item['date']] = $item;
}
foreach($object as $item)
{
$finalArray[$item->post->date] = json_decode(json_encode($item), TRUE);
}
ksort($finalArray);
foreach($finalArray as $date => $item)
{
// Everything is an array now
}

Basic implode foreach

I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Why are you assigning $elements = $array; and then never using $elements?
Also you don't need to loop (foreach) to implode an array.
Try this:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
// this array_push() function adds $value to the end of $new_array.
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Here is the documentation on implode()
You can play around and test the above code here.
Also next time, add the tag php, otherwise our codes won't get color syntax.

Categories