Access array by its numeric index - php

I have this array
Array ( [name] => guardian [url] => http://www.guardian.co.uk )
Array ( [name] => cnn [url] => http://www.cnn.com )
which i am accessing like
$das_repeat = get_post_meta($post->ID, 'repeatable_fields', true);
foreach ( $das_repeat as $fiel ) {
echo $fiel['name'].'<br/>';
//print_r($fiel);
}
However, i am very interested in accessing each value by its numeric index.How can i reindex $fiel['name'] to allow me access each value by its index?.

Your array does not have numeric indices, it does not really make sense to access it by numeric indices. You can strip all the keys out and reindex the array numerically:
$reindexed = array_values($das_repeat);
However, again, it doesn't really make sense to do so. If you want to iterate over the array without knowing its keys, you're already doing that using foreach.

To re-index an array you can use array_values.
$array = array(
'name' => 'A name',
'attr2' => 'Attr 2'
);
$array = array_values($array);
var_dump($array);
Result:
array
0 => string 'A name' (length = 6)
1 => string 'Attr 2' (length = 6)
Although, as #deceze pointed out, this has the potential to cause bugs and/or unexpected behavior in your code, so use wisely. For example, think about what will happen if, for some reason, the 1st post meta will be deleted. All the information you show will be wrong.
Note: Is not recursive

foreach ( $das_repeat as $id => $fiel ) {
echo $fiel['name'].'<br/>';
//print_r($fiel);
// $id not contains the index
}

Use array_values.
foreach ( $das_repeat as $fiel ) {
$field = array_values($fiel);
echo $field[0]; //will output guardian and then cnn
}

As other answers say, you can use array_values to create a new array with the same values, but numeric indices. If you want to keep the associative array as it is, but also access it numerically, you could do this:
$keys = array_keys($das_repeat);
$elementN = $das_repeat[$keys[$N]];

Related

Fast searching approach in multidimensional array

The above searching I want with minimum number of code and with best serach performance.
I want to generate an array from this above array by putting logic like:
ALL "EMA" key values of array should not be allowed to match with "JACKSON" key values. Similarly all "JACKSON" key values of the same array are not allowed to fall in any value of "EMA" key. So the resulting array would be like shown below:
Array
(
[0] => Array
(
[EMA] => A
[JACKSON] => B
)
[2] => Array
(
[EMA] => D
[JACKSON] => E
)
)
I want to know the best approach with lesser code to achieve this. The method I have used seems so lengthy. I want a shorter and robust approach.
I think this might be a solution:
$emas = array();
$jacksons = array();
foreach($array as $element){
$emas[] = $element['EMA'];
$jacksons[] = $element['JACKSON'];
}
//array_intersect returns the common values in the arrays as an array
if(!empty(array_intersect($emas, $jacksons))){
echo 'array is invalid!';
}

Get all array data with a certain string

I want to get all the array data where keys has the characters 'ch' from the start. How do I get it?
Array ( [editpostid] => 0 [editpostcat] => 1 [ch114] => on [ch115] => on )
The keys of the data may vary as the numbers come from the record id's from the database.
how do I place all the data with 'ch' in the start of keys on to a separate array?
Do like this
<?php
$arr = array('ch'=>10,'abch'=>20,'ch23'=>45);
$newarr=array();
foreach($arr as $k=>$v)
{
if(substr(strtolower($k),0,2)=='ch')
{
array_push($newarr,$v); // Make use of this if you just need the values
//$newarr[$k]=$v; // Uncomment this and comment above statement, if you need the keys too
}
}
print_r($newarr);
OUTPUT:
Array
(
[0] => 10
[1] => 45
)
$charray=array();
foreach($yourarray as $key=>$value){
if(preg_match("/^ch/",$key)){
$charray[$key]=>$value;
}
}
//$charray is the new arrayas you asked for
echo implode(',',$charray);
refer official documentation for preg_match for more information

Associative Array display not working

I am trying to call an associative array and I am confused why this would not work.
if I print_r($test); it shows the following:
Array(
[e7a36fadf2410205f0768da1b61156d9] => Array(
[rowid] => e7a36fadf2410205f0768da1b61156d9
[id] => 3
[qty] => 1
[price] => 20
[name] => test
[options] => Array(
[permName] => large
)
[subtotal] => 20
)
)
but if I do $test[0]["rowid"]; it gives the following error Message: Undefined offset: 0
I am still a php newbie but from what I have learned about arrays so far this should work. Any ideas?
Thanks
Your array is associative so $test[0] doesn't exist.
$test['e7a36fadf2410205f0768da1b61156d9']['rowid']
If you want to get the first element without referencing the key you can use reset($test)
$first_element = reset($test);
$first_element['row_id'];
The two examples are functionality identical.
Your outter array seems to have the key "e7a36fadf2410205f0768da1b61156d9" - its not indexed numerically.
So you should use
$test["e7a36fadf2410205f0768da1b61156d9"]["rowid"]
You can also use array_keys if you want to find out what the first non-numerical key is
You either can use key $test['e7a36fadf2410205f0768da1b61156d9']['rowid'] as [Mike B suggested][1]. Or get first element of array with [reset()`]2:
$element = reset( $test);
$element['rowid'];
Or use array_keys() if you will need to work with those keys later (you can always get current key with key()):
$keys = array_keys( $test);
$test[ $keys[0]]['rowid'];
And if you need to browse all records in test just use foreach:
foreach( $test as $key => $item){
$item['rowid'];
}

How to convert a 2-dim array of strings into 1-dim array of trimmed, unique values?

I have an array whose values are all arrays of a specific format that looks like this:
Array
(
[0] => Array
(
[0] => '8227'
[1] => ' 8138'
)
[1] => Array
(
[0] => '8227'
[1] => ' 8138'
[2] => ' 7785'
)
)
and I would like to have this:
Array
(
[0] => 8227
[1] => 8138
[2] => 7785
)
How can I do this ?
$result = array();
foreach ($input as $sub) { // Loop outer array
foreach ($sub as $val) { // Loop inner arrays
$val = trim($val);
if (!in_array($val, $result)) { // Check for duplicates
$result[] = $val; // Add to result array
}
}
}
$result = array();
foreach($array as $arr){
$result = array_merge($result, $arr);
}
$result = array_unique($result);
array_merge_recursive() can be used to flatten the array. Then, array_unique() to get the unique values, with array_values() to "reindex" the resultant array.
$flat = call_user_func_array('array_merge_recursive', $subject);
$uniq = array_values(array_unique($flat));
<?php
$array = array(
0 => array(
0 => 8227,
1 => 8138
),
1 => array(
0 => 8227,
1 => 8138,
2 => 7785
)
);
$newArray = array();
array_walk_recursive($array, function($item, $key) use(&$newArray) {
if(!in_array($item, $newArray)) {
$newArray[] = $item;
}
});
print_r($newArray);
?>
I don't like the idea of iterated calls of in_array() since it can cause a bit of drag on big arrays.
Now, my methods to follow are probably not going to set any speed records (I didn't bother to benchmark), but I thought I would post a couple of unorthodox approaches in case they may inspire future readers.
Method #1:
convert the multi-dimensional array to a json string
split the string on all non-digital substrings (this also trims the values)
eliminate duplicates using array_flip()
re-index the resultant array using array_keys() (output values are integer-type)
Method #2:
convert the multi-dimensional array to a json string
extract the words (which in this case include numbers and there aren't any letters to worry about)
eliminate duplicates using array_flip()
reindex the resultant array using array_keys() (output values are integer-type)
Code: (Demo)
$array = [['8227', '8138'], [' 8227', ' 8138', ' 7785']];
echo "regex method: ";
var_export(
array_keys(
array_flip(
preg_split(
'/\D+/',
json_encode($array),
0,
PREG_SPLIT_NO_EMPTY
)
)
)
);
echo "\n\nnon-regex method: ";
var_export(
array_keys(
array_flip(
str_word_count(
json_encode($array),
1,
'0..9'
)
)
)
);
Output:
regex method: array (
0 => 8227,
1 => 8138,
2 => 7785,
)
non-regex method: array (
0 => 8227,
1 => 8138,
2 => 7785,
)
If either of these methods perform well, it will be because they don't make iterated function calls.
p.s. Okay, because I was curious, I just did a very small / unofficial speed test on my two methods and DaveRandom's method (only 1000 iterations using the OP's data - I didn't want to abuse 3v4l.org) and...
Method #1 ran about as fast as Method #2
Both Method #1 and Method #2 ran faster than DaveRandom's method.
Again, I'll state that fabricated tests for micro-optimization may be pointless and real tests should be done on your REAL data IF it is actually important. If you merely prefer the logical flow of another answer on this page, I totally respect that.

Traversing all values of an array of arrays

N in this question means any arbitrary number of any size and is not necessarily (but could be) the same. I have an array with N number of key => value pairs. These key => value pairs can also contain another array of size N with N number of key => value pairs. This array can be of N depth, meaning any key => value pair in the array could map to another array.How do I get all the values of this array (storing them in a new, 1 dimensional array), ignoring the keys in the key => value pairs?
array-walk-recursive
rob at yurkowski dot net 26-Oct-2010
06:16
If you don't really particularly
care about the keys of an array, you
can capture all values quite simply:
$sample = array(
'dog' => 'woof',
'cat' => array(
'angry' => 'hiss',
'happy' => 'purr'
),
'aardvark' => 'kssksskss'
);
$output = array();
// Push all $val onto $output.
array_walk_recursive($sample, create_function('$val, $key, $obj', 'array_push($obj, $val);'), &$output);
// Printing echo nl2br(print_r($output, true));
/*
* Array
* (
* [0] => woof
* [1] => hiss
* [2] => purr
* [3] => kssksskss
* )
*/
You could do smt like this:
$output = array();
function genArray( $arr ) {
global $output;
foreach( $arr as $key => $val ) {
if( is_array($val) )
genArray( $val );
else
output[$key] = $val;
}
}
genArray( $myArray );
Instead of recursion, using global variable and function, it could be done via loops, but this is just a general idea, and probably needs a little of your attention, anyway. That should be a good thing :)
There are a ton of solutions in the comments of the array_values php doc.
http://www.php.net/manual/en/function.array-values.php

Categories