Move to previous entry with ArrayIterator? - php

$list = new ArrayIterator(array('page1', 'page2', 'page3', 'page4'));
echo $list->current(); // 'page1'
$list->next();
echo $list->current(); // 'page2'
// What I want to achieve
$list->previous();
echo $list->current(); // 'page1'
From there, how can I get last element page1 ?

You can use seek() method and key index to move internal pointer to last element
$list->seek($list->key() - 1);
Full example
$list = new ArrayIterator(array('page1', 'page2', 'page3', 'page4'));
echo $list->current(); // 'page1'
$list->next();
echo $list->current(); // 'page2'
$list->seek($list->key() - 1);
echo $list->current(); // 'page1'

I had this problem with an associative ArrayIterator, and this works both for simple and associative arrays, if you track the numeric position of the pointer as you cycle through the array ...
$list = new ArrayIterator(
[
'foo' => 'page1',
'bar' => 'page2',
'baz' => 'page3',
'qux' => 'page4',
'fred' => 'page5'
]
);
$numericIndex = -1;
foreach ($list as $key => $value) {
$numericIndex++;
var_dump($list->current());
if ($key === 'bar') {
// Jump ahead to do stuff to the following elements
$list->next();
var_dump('Jumped ahead to: ' . $list->current());
$list->next();
var_dump('Jumped ahead to: ' . $list->current());
// Rewind to original position to continue the loop
$list->seek($numericIndex);
}
}
That outputs:
...:string 'page1' (length=5)
...:string 'page2' (length=5)
...:string 'Jumped ahead to: page3' (length=22)
...:string 'Jumped ahead to: page4' (length=22)
...:string 'page3' (length=5)
...:string 'page4' (length=5)
...:string 'page5' (length=5)

Related

Other ways to add element in an array?

$a = ['foo' => 'bar'];
If I want to add new elements in this array I would usually write this
$a['foo2'] = 'bar2';
$a['foo3'] = 'bar3';
$a['foo4'] = 'bar4';
Is there some other syntax so I can add elements like this without overwriting $a?
$a = [ 'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
You can also do something like this:
$arr1 = array('foo2' => 'bar2');
$arr2 = array('foo3' => 'bar3');
$arr3 = $arr1 + $arr2;
You can use array_merge to add an array to the end of another array.
$a = array_merge($a, $b);
where $b is:
$b = [ 'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
Or just do:
$a = ['foo' => 'bar'];
$a = array_merge([$a,'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
Will return what you want.
You could create a simple Function for that like so:
<?php
/**
* #param $mainArray => THE ARRAY TO WHICH OTHER ELEMENTS (INCL. ARRAYS/OBJECTS) SHOULD BE ADDED
* #param $data => A KEY-VALUE PAIR ARRAY OR A NORMAL STRING/NUMBER
* #return array
*/
function arrayAdd(&$mainArray, $data){
if(is_array($data)){
foreach($data as $k=>$v){
$mainArray[$k] = $v;
}
}else if(is_string($data)){
$mainArray[] = $data;
}
return $mainArray;
}
// CREATE A OBJECT (TO SHOW IT COULD ALSO HANDLE THAT AS WELL)
$obj = new stdClass();
$obj->name = 'Some Name';
$obj->tel = '+1 202 532 00 00 00';
// THE MAIN ARRAY TO WHICH OTHER ELEMENTS SHOULD BE ADDED
$main = ['foo1' => 'bar1', 'foo2' => 'bar2'];
// A COLLECTION OF DATA TO ADD TO $main
$data = [
'one' => 'Un',
'two' => 'Deux',
'three' => 'Trois',
'four' => 'Quart',
'obj' => $obj,
];
// CALL THE FUNCTION AND PASS THE PARAMETERS
var_dump( arrayAdd($main, $data) );
// YIELDS::
array (size=7)
'foo1' => string 'bar1' (length=4)
'foo2' => string 'bar2' (length=4)
'one' => string 'Un' (length=2)
'two' => string 'Deux' (length=4)
'three' => string 'Trois' (length=5)
'four' => string 'Quart' (length=5)
'obj' =>
object(stdClass)[1]
public 'name' => string 'Some Name' (length=9)
public 'tel' => string '+1 202 532 00 00 00' (length=19)
How about this ?
I think it is simplest to add element into an array
<?php
$cart = [];
//to add one
array_push($cart, 13);
// to add multiple
array_push($cart, 13,14,15);
?>

PHP Array Create from given Array

Thsi is my array structure.
$arr = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
I want to create an array like this.
array
0 =>
array
'Tablet' => string 'test1' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode1' (length=9)
'Since' => string 'mng' (length=3)
1 =>
array
'Tablet' => string 'test2' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode2' (length=9)
'Since' => string 'mng' (length=3)
Can someone pls help?
Sorry for bad english.
Thanks
$new = [];
foreach ($arr as $key => $sub) {
$i = 0;
foreach ($sub as $value) {
$new[$i][$key] = $value;
$i++;
}
}
That should do the trick :)
$newArr = array();
foreach ( $arr as $key => $subArr ){
for ($i= 0; $i < count($subArr); $i++){
if (!array_key_exists($i, $newArr)){
$newArr[$i] = array();
}
$newArr[$i][$key] = $subArr[$i];
}
}
$arr = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1','abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$na=array();
foreach($arr as $k=>$v){
foreach($v as $kk=>$vv){
$na[$kk][$k]=$vv;
}
}
echo "<pre>";print_r($na);
Easy you can append each one to normal array like this
$arr1 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$arr2 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$arr3 = array(
'Tablet'=>array('test1','test2'),
'Medicine'=>array('abc1'.'abc2'),
'Dosage'=>array('1','1'),
'Mode'=>array('testmode1','testmodel2'),
'Since'=>array('mng','mng')
);
$a=array();
array_push($a,arr1,arr2,arr3);
print_r($a);
output will look
array
0 =>
array
'Tablet' => string 'test1' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode1' (length=9)
'Since' => string 'mng' (length=3)
1 =>
array
'Tablet' => string 'test2' (length=5)
'Medicine' => string 'abc1' (length=4)
'Dosage' => string '1' (length=1)
'Mode' => string 'testmode2' (length=9)
'Since' => string 'mng' (length=3)
$myLength = count($arr['Tablet'])
$newArray = array();
for (i=0; i < $myLength ; i++)
{
$newArray[i]['Tablet'] = $arr['Tablet'][i];
$newArray[i]['Medicine'] = $arr['Medicine'][i];
$newArray[i]['Dosage'] = $arr['Dosage'][i];
$newArray[i]['Mode'] = $arr['Mode'][i];
$newArray[i]['Since'] = $arr['Since'][i];
}
What do you meant adding the (lentgh = x) in your question?

Switching two keys of an array

I feel like I am so close to successfully switching Jim and Jill in this associative array. I ALSO would like it to be repeatable, so if 'Joe' is added to the end, it will also swap 'Jim' and 'Joe.' Any pointers?
<?php
function jim_is_jill($their_name) {
$first = key($their_name);
foreach ($their_name as $key => $value) {
$lastmaybe = $key;
}
$lastmaybe = $these; // Lastmaybe is Jill
$these = $first;
return $their_name;
}
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
print_r(jim_is_jill($their_name));
?>
CURRENT OUTPUT:
Array
(
[Jim] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jill] => daughter
)
DESIRED OUTPUT:
Array
(
[Jill] => dad
[Josh] => son
[Jamie] => mom
[Jane] => daughter
[Jim] => daughter
)
Considering the array
$their_name = array(
// Key => Value
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
This function will produce :
function array_swap_values($array, $key1, $key2) {
$temp = $array[$key1];
$array[$key1] = $array[$key2];
$array[$key2] = $temp;
return $array;
}
$their_name = array_swap_values($their_name, 'Jim', 'Jill');
// -> array(
// 'Jim' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jill' => 'dad'
// );
Or this function will produce
function array_swap_keys($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key2];
} else if ($key === $key2) {
$ret[$key1] = $array[$key1];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_keys($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'daughter',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'dad'
// );
** Update **
After your last edit, I modified the last function to return what is expected. It is pretty close to the first function, but it preserve the key ordering :
function array_swap_key_value($array, $key1, $key2) {
$ret = array();
foreach ($array as $key => $value) {
if ($key === $key1) {
$ret[$key2] = $array[$key1];
} else if ($key === $key2) {
$ret[$key1] = $array[$key2];
} else {
$ret[$key] = $value;
}
}
return $ret;
}
$their_name = array_swap_key_value($their_name, 'Jim', 'Jill');
// -> array(
// 'Jill' => 'dad',
// 'Josh' => 'son',
// 'Jamie' => 'mom',
// 'Jane' => 'daughter',
// 'Jim' => 'daughter'
// );
First thing, in my experience, it's not wise to rely on the order of an array, if it is not indexed by numbers. There are no tools (correct me if I'm wrong) to switch positions of keys or change keys themselves. It would have to be ugly hack. The only way to rename a key is to remove it and put it back correctly. But that disturbs the order of an array. You'll really have to rebuild the array from scratch, that's an easiest way, as suggested by Yanick, if you really want to do what you want to do. But there's more neat solution. You can make an array with numbered indexes, which you-shall-not-touch. That way, it will stay order. Then put simple small array in each value:
array('name'=> 'Jill, 'relationship'=>'daughter);
That way, you have full control of the order of indexes (thanks to numbered indexes) and you will only have to swap values, which is dead easy.
Or, you can omit those words and give it just numbered indexes everywhere. That way you'll write less but you will have to remember which is which:
array('jill', 'daughter');
is effectively same as:
array(0 => 'Jill', 1 => 'daughter');
So here's the code..
<?php
function swap_first_and_last($their_name) {
//get first and last keys
reset($their_name); // resets the array pointer to beginning
$k_first=key($their_name); // first key
end($their_name);
$k_last=key($their_name); // last key
// swap first and last:
$swap = $their_name[$k_first]['name'];
$their_name[$k_first]['name']=$their_name[$k_last]['name'];
$their_name[$k_last]['name']=$swap;
// note: you can use [0] and [1], if you modify your array that way
return $their_name;
}
// modified array
$their_name = array(
// note, you can omit those 0 => , 1 => ,2,... keys
0 => array('name' => 'Jim', 'relationship' => 'dad'),
1 => array('name' => 'Josh', 'relationship' => 'son'),
2 => array('name' => 'Jamie', 'relationship' => 'mom'),
3 => array('name' => 'Jane', 'relationship' => 'daughter'),
4 => array('name' => 'Jill', 'relationship' => 'daughter')
);
var_dump(swap_first_and_last($their_name));
And the result is:
array (size=5)
0 =>
array (size=2)
'name' => string 'Jill' (length=4)
'relationship' => string 'dad' (length=3)
1 =>
array (size=2)
'name' => string 'Josh' (length=4)
'relationship' => string 'son' (length=3)
2 =>
array (size=2)
'name' => string 'Jamie' (length=5)
'relationship' => string 'mom' (length=3)
3 =>
array (size=2)
'name' => string 'Jane' (length=4)
'relationship' => string 'daughter' (length=8)
4 =>
array (size=2)
'name' => string 'Jim' (length=3)
'relationship' => string 'daughter' (length=8)

Finding and echoing anchor tags in a php file

I have searched a lot for this but have not yet found anything that works...
I would like to find all the anchor tags in another php file and echo their names (with an href to their location in the document).
For example, I have this in one file:
<a name="test"></a>
and would like to find all of them using some code in my main php file and print them all...
Here's what I've tried:
$dom = new DOMDocument;
$dom->loadHTML($content);
foreach( $dom->getElementsByTagName('a') as $node ) {
echo $node->getAttribute( 'name' );
}
I know it's not exactly super specific but yeah, thanks.
EDIT: How about a way to find and echo anchors on the current page?
look here for the actual site: http://robertwbooth.co.uk
You can try
$html = file_get_html("http://xxxxxx/support/content-entry/create-anchor-tags/");
$anchor = array();
foreach ( $html->find("a") as $link ) {
if ($link->href === false) {
$key = $link->id ? $link->id : ($link->name ? $link->name : false);
if (! $key)
continue;
if (isset($anchor[$link->id])) {
$anchor[$link->id] = array_merge($anchor[$link->id], array("name" => $link->name,"id" => $link->id));
} else {
$anchor[$link->id] = array("name" => $link->name,"id" => $link->id);
}
} else {
if (strpos($link->href, "#") === 0) {
if (isset($anchor[substr($link->href, 1)])) {
$anchor[substr($link->href, 1)] = array_merge($anchor[substr($link->href, 1)], array("text" => $link->plaintext));
} else {
$anchor[substr($link->href, 1)] = array("text" => $link->plaintext);
}
}
}
}
var_dump($anchor);
Output
array
'id507d815fd9383' =>
array
'name' => string 'id507d815fd9383' (length=15)
'id' => string 'id507d815fd9383' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93a3' =>
array
'name' => string 'id507d815fd93a3' (length=15)
'id' => string 'id507d815fd93a3' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93bc' =>
array
'name' => string 'id507d815fd93bc' (length=15)
'id' => string 'id507d815fd93bc' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93d3' =>
array
'name' => string 'id507d815fd93d3' (length=15)
'id' => string 'id507d815fd93d3' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd93eb' =>
array
'name' => string 'id507d815fd93eb' (length=15)
'id' => string 'id507d815fd93eb' (length=15)
'text' => string 'Visit the Useful Tips Section' (length=29)
'id507d815fd9404' =>
array
.......... so many more

Unique PHP Array

How can I check if the values are unique in an array based on the key value? Below is the out put of the array. I want to remove duplicate values based on the "id" key. If you check below, the 2nd & 3rd array are same except for the "role" value. Because of this, array_unique is not working on this array.
array
0 =>
array
'id' => string '1521422' (length=7)
'name' => string 'David Alvarado' (length=14)
'role' => string 'associate producer ' (length=20)
1 =>
array
'id' => string '0098210' (length=7)
'name' => string 'Cristian Bostanescu' (length=19)
'role' => string 'line producer: Romania (as Cristi Bostanescu)' (length=46)
2 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'co-producer ' (length=13)
3 =>
array
'id' => string '1266015' (length=7)
'name' => string 'Bruno Hoefler' (length=13)
'role' => string 'executive producer ' (length=20)
4 =>
array
'id' => string '1672379' (length=7)
'name' => string 'Alwyn Kushner' (length=13)
'role' => string 'associate producer ' (length=20)
Try this one:
<?php
$array = array(
array('id' => 1, 'text' => 'a'),
array('id' => 2, 'text' => 'b'),
array('id' => 1, 'text' => 'c'),
array('id' => 3, 'text' => 'd')
);
$array = array_filter($array, function ($item) {
static $found = array();
if (isset($found[$item['id']])) return false;
$found[$item['id']] = true;
return true;
});
var_dump($array);
This works as of PHP 5.3 (because of the closure and static statement).
cf. http://php.net/manual/en/function.array-filter.php for more information. I tested the statement within loops, it works there as well.
Basically you want to implement a variation of array_unique that does what you want:
function array_unique_multi($arr,$key='id') {
// $arr is the array to work on
// $key is the key to make unique by
$ret = Array();
foreach($arr as $v) {
if( !isset($ret[$v[$key]])) $ret[$v[$key]] = $k;
}
return array_values($ret);
}
You can use this code:
// assuming $arr is your original array
$narr = array();
foreach($arr as $key => $value) {
//$narr[json_encode($value)] = $key;
if (!array_key_exists($value["id"], $narr))
$narr[$value["id"]] = $key;
}
$narr = array_flip($narr);
foreach($arr as $key => $value) {
if (!array_key_exists($key, $narr))
unset($arr[$key]);
}
print_r($arr); // will have no duplicates

Categories