Accessing the nth element in multidimensional array - php

is there a simple way to access the nth element in a multidimensional array in php?
so for example
$arr = array(
[0] => array(1,4,7,3,53),
[6] => array(6,3,9,12,51,7),
[2] => array(9,94,54,3,87));
the 12th element would be 9.
array keys are not necessarily in order, nor each array row is of the same length.

Try this :
<?php
$arr = array(
'0'=> array(1,4,7,3,53),
'6'=>array(6,3,9,12,51,7),
'2'=>array(9,94,54,3,87)
);
$newArray=array();
foreach($arr as $array){
$newArray=array_merge($newArray, $array);
}
echo $newArray[11];
?>

untested, should work...
$arr = array(
0 => array(1,4,7,3,53), // your code was wrong here
6 => array(6,3,9,12,51,7),
2 => array(9,94,54,3,87));
function getnth ($array, $offset) {
$tmp_arr = array();
foreach ($array as $key => $value) {
foreach ($value as $val) {
$tmp_arr[] = $val;
}
}
return (isset($tmp_arr[$offset -1]) ? $tmp_arr[$offset -1] : FALSE);
}
getnth($arr, 12);
Edit: got to admit, the array_merge version is better....
Edit2: this is probably faster, if performance is an issue....
function getnth($array, $offset) {
$i = 0;
foreach ($array as $key => $value){
$size = count($value);
$i += $size;
if($offset <= $i) {
$new_off = $size - ($i - $offset) -1 ;
return $value[$new_off];
}
}
return FALSE;
}

function get_item($arr, $path, $delim = '.') {
$path = explode($delim, $path);
$result = $arr;
foreach ($path as $item) {
if (isset($result[$item])) {
$result = $result[$item];
} else {
return null;
}
}
return $result;
}
using:
echo get_item($arr, 'item.value.3.4.2.etc');

Related

Split an array by key

I have an array with the following keys:
Array
{
[vegetable_image] =>
[vegetable_name] =>
[vegetable_description] =>
[fruit_image] =>
[fruit_name] =>
[fruit_description] =>
}
and I would like to split them based on the prefix (vegetable_ and fruit_), is this possible?
Currently, I'm trying out array_chunk() but how do you store them into 2 separate arrays?
[vegetables] => Array { [vegetable_image] ... }
[fruits] => Array { [fruit_image] ... }
This should work for you:
$fruits = array();
$vegetables = array();
foreach($array as $k => $v) {
if(strpos($k,'fruit_') !== false)
$fruits[$k] = $v;
elseif(strpos($k,'vegetable_') !== false)
$vegetables[$k] = $v;
}
As an example see: http://ideone.com/uNi54B
Out of the Box
function splittArray($base_array, $to_split, $delimiter='_') {
$out = array();
foreach($to_split as $key) {
$search = $key.delimiter;
foreach($base_array as $ok=>$val) {
if(strpos($ok,$search)!==false) {
$out[$key][$ok] = $val;
}
}
return $out;
}
$new_array = splittArray($array,array('fruit','vegetable'));
It is possible with array_reduce()
$array = ['foo_bar' => 1, 'foo_baz' => 2, 'bar_fee' => 6, 'bar_feo' => 9, 'baz_bee' => 7];
$delimiter = '_';
$result = array_reduce(array_keys($array), function ($current, $key) use ($delimiter) {
$splitKey = explode($delimiter, $key);
$current[$splitKey[0]][] = $key;
return $current;
}, []);
Check the fiddle
Only one thins remains: you are using different forms (like "vegetable_*" -> "vegetables"). PHP is not smart enough to substitute language (that would be English language in this case) transformations like that. But if you like, you may create array of valid forms for that.
Use explode()
$arrVeg = array();
$arrFruit = array();
$finalArr = array();
foreach($array as $k => $v){
$explK = explode('_',$k);
if($explK[0] == 'vegetable'){
$arrVeg[$k] = $v;
} elseif($explK[0] == 'fruit') {
$arrFruit[$k] = $v;
}
}
$finalArr['vegetables'] = $arrVeg;
$finalArr['fruits'] = $arrFruit;
Use simple PHP array traversing and substr() function.
<?php
$arr = array();
$arr['vegetable_image'] = 'vegetable_image';
$arr['vegetable_name'] = 'vegetable_name';
$arr['vegetable_description'] = 'vegetable_description';
$arr['fruit_image'] = 'fruit_image';
$arr['fruit_name'] = 'fruit_name';
$arr['fruit_description'] = 'fruit_description';
$fruits = array();
$vegetables = array();
foreach ($arr as $k => $v) {
if (substr($k, 0, 10) == 'vegetable_') {
$vagetables[$k] = $v;
}
else if (substr($k, 0, 6) == 'fruit_') {
$fruits[$k] = $v;
}
}
print_r($fruits);
print_r($vagetables);
Working Example

how to convert index array to associative array?

I have an array like that
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
and i want to achieve array like that
$arrProducts= array(array('product_id'=>354,'qty'=>1),array('product_id'=>375,'qty'=>1),array('product_id'=>344,'qty'=>2));
I achieved this array using this code
foreach($products as $val)
{
$abc[] =$val[0];
}
for($i=0;$i<count($abc);$i++)
{
if($i%2==0)
{
$newarr[]['product_id'] = $abc[$i];
}
else{
$newarr[]['qty'] = $abc[$i];
}
}
for($j=0;$j<count($newarr);$j++)
{
if($j%2==0)
{
$arrProducts[] = array_merge($newarr[$j],$newarr[$j+1]);
}
else{
continue;
}
}
echo '<pre>';
print_r($arrProducts);
but i think my way to get this array is too long so how can i get this array in short way using some array functions or should i use this code?
You can use array_chunk in this case if this is always by twos, and combine it with array_combine():
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$products = array_chunk($products, 2);
$arrProducts = array();
$keys = array('product_id', 'qty');
foreach($products as $val) {
$arrProducts[] = array_combine($keys, array(reset($val[0]), reset($val[1])));
}
echo '<pre>';
print_r($arrProducts);
Another alternative would be:
$products = array(array(354),array(1),array(375),array(1),array(344),array(2));
$keys = array('product_id', 'qty');
$arrProducts = array_map(function($e) use ($keys) {
return array_combine($keys, array_map('reset', $e));
}, array_chunk($products, 2));
This will yield the same result.
Consume two array elements on each iteration:
$arrProducts = array();
$inputLength = count($products);
for ($i = 0; $i < $inputLength; $i += 2) {
$arrProducts[] = array('product_id' => $products[$i][0], 'qty' => $products[$i+1][0]);
}
$i=1;
$j=0;
foreach($products as $val)
{
if(($i%2) == 0)
{
$abc[$j]['qty'] =$val[0];
$j++;
}
else
{
$abc[$j]['product_id'] =$val[0];
}
$i++;
}

PHP - Multidimensional array to CSV

I currently have coded a way to turn a multidimensional array to comma separated values (I'm using pipes instead of commas for ease of debugging). The problem is, I know that the code I use to do this is bloody awful. It works how I want it to, but it's not nice at all.
What I need
Currently the arr_to_csv() function works for five levels of nested data within the multidimensional array. I need a recursive function to perform the same for one or an unlimited number of nested arrays, or a good nudge in the right direction. Recursion is not my strong point at all, but I know it's the way forward.
Data input
A multi-dimensional array is passed to the function.
array
'name' =>
array
'singular' => null
'plural' => null
'fields' =>
array
'price' =>
array
'label' => string 'Preis' (length=5)
'company_id' =>
array
'label' => null
'placeholder' => null
//...the array could go on...
The function returns the following...
This is exactly what I want...
0 => string 'name||singular||null' (length=20)
1 => string 'name||plural||null' (length=18)
2 => string 'fields||price||label||Preis' (length=27)
3 => string 'fields||company_id||label||null' (length=31)
4 => string 'fields||company_id||placeholder||null' (length=37)
5 => string 'fields||name||label||null' (length=25)
6 => string 'fields||name||placeholder||null' (length=31)
My horrible constructed function
I'm no good with recursion, so here's my awful list of foreachs. As you can see from the below code, this is terrible (no need to read the whole thing, it just copies itself). Please help me sort out my horrible code!
function arr_to_csv($data,$csv = '||') {
$array = array();
/* Epic amount of for each's. This could be done with recursion */
foreach($data as $key => &$value) {
if (!is_array($value)) {
$array[] = $key . $csv .(is_null($value)?'null':$value);
} else {
foreach ($value as $k => &$v) {
if (!is_array($v)) {
$array[] = $key . $csv . $k . $csv . (is_null($v) ? 'null' : $v);
} else {
foreach ($v as $kk => &$vv) {
if (!is_array($vv)) {
$array[] = $key . $csv . $k . $csv . $kk . $csv . (is_null($vv) ? 'null' : $vv);
} else {
foreach ($vv as $x => &$y) {
if (!is_array($y)) {
$array[] = $key . $csv . $k . $csv . $kk . $csv. $x . $csv . (is_null($y) ? 'null' : $y);
} else {
foreach ($y as $too => $long) {
if(!is_array($long)) {
$array[] = $key . $csv . $k . $csv . $kk . $csv. $x . $csv . $too . $csv. (is_null($long)?'null':$long);
} else {
foreach ($long as $omg => $why) {
if(!is_array($why)) {
$array[] = $key . $csv . $k . $csv . $kk . $csv. $x . $csv . $too . $csv . $omg . $csv . (is_null($why) ? 'null' : $why);
}
}
}
}
}
}
}
}
}
}
}
}
return $array;
}
This is some pseudocode, but it is a start:
$strings = [];
$flattenArray = function($arr, $level) use (&$strings, &$flattenArray) {
foreach($arr as $key=>$value){
$s = &$strings[$level];
if(!isset($s)) { $s = array(); }
$s[] = $key;
if(is_array($value)) {
$flattenArray($value, $level);
}
else {
$s[] = $value;
}
$level ++;
}
};
$flattenArray($myArray, 0);
foreach($strings as &$arr) {
$arr = implode("||", $arr);
}
Small demo with your array: http://codepad.viper-7.com/CR2SPY <-- It does not work fully, but it is a start
Update:
Here is a demo that I think works the way you want: http://codepad.viper-7.com/shN4pH
Code:
$strings = [];
$flattenArray = function($arr, $level, $k = null) use (&$strings, &$flattenArray) {
foreach($arr as $key=>$value){
if($k === null) {
$s = &$strings[$key];
}
else {
$s = &$strings[$k];
}
if(!isset($s)) {
$s = array();
}
$str = &$s[$level];
if(!isset($str)) {
$str = array();
if($k !== null) { $str[] = $k; }
}
$str[] = $key;
if(is_array($value)) {
$flattenArray($value, $level, ($k === null) ? $key : $k);
}
else {
$str[] = is_null($value) ? "null" : $value;
}
$level ++;
}
};
$flattenArray($myArray, 0);
$all = [];
foreach($strings as $k => $arr){
$new = array();
foreach($arr as $ky => $ar) {
$all[] = implode("||", $ar);
}
}
print_r($all);
I didn't check it, so in case it doesn't work it should be corrected.
function readarray($from_array, $addr = array()) {
global $output;
foreach ($from_array as $key => $value) {
if (is_Array($value) && count($value) > 0) {
$addr[] = $key;
readarray($value, $addr);
} else {
$output[] = implode('||', $addr) . $value;
}
}
}
$output = array();
foreach ($my_array as $key=>$value){
readarray($value);
}
// improved to get separate arrays of the root of initial array
Not sure if this will help you, but would it not be easier to flatten the array first and then format in in the way you want? To flatten the array try this:
$array = "YOUR ARRAY";
$FlatArray = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k=>$v)
{
$FlatArray[$k] = $v;
}
Been trying all morning to come up with a recursive function for this. This is as close as I got, Maybe you can improve upon this.
$data = array('name' =>array('singular' => NULL,'plural' => NULL,'fields' =>array('price' =>array('label' =>'Preis','company_id' =>array('label' => NULL,'placeholder' => NULL)))));
function arr_to_csv($data,$csv = '||')
{
$list = "";
foreach($data as $key => &$value)
{
$list .= $key . $csv .((!is_array($value))?(is_null($value)?'null':$value): arr_to_csv($value))."<br>";
}
return $list;
}
print_r(arr_to_csv($data));
Returns This:
name||singular||null
plural||null
fields||price||label||Preis
company_id||label||null
placeholder||null

PHP - Mutidimensional array diff

i would like to ask for your help since I'm having difficulty resolving this matter. I had created a function to facilitate on array diff but it does not suffice to my needs. Thanks and more power!
<?php
$arraySession = array(
'sampleA' => array('1', '2', '3'),
'sampleB' => array('1', '2', '3'),
);
$arrayPost = array(
'sampleA' => array('1'),
'sampleB' => array('1','2'),
);
result should be:
array(
'sampleA' => array('2', '3')
'sampleB' => array('3'),
)
my existing function:
public function array_diff_multidimensional($session, $post) {
$result = array();
foreach($session as $sKey => $sValue){
foreach($post as $pKey => $pValue) {
if((string) $sKey == (string) $pKey) {
$result[$sKey] = array_diff($sValue, $pValue);
} else {
$result[$sKey] = $sValue;
}
}
}
return $result;
}
Any help would be much appreciated! Happy coding!
Not my function and not tested by me, but this was one of the first comments at php.net/array_diff (credit goes to thefrox at gmail dot com)
<?php
function multidimensional_array_diff($a1, $a2) {
$r = array();
foreach ($a2 as $key => $second) {
foreach ($a1 as $key => $first) {
if (isset($a2[$key])) {
foreach ($first as $first_value) {
foreach ($second as $second_value) {
if ($first_value == $second_value) {
$true = true;
break;
}
}
if (!isset($true)) {
$r[$key][] = $first_value;
}
unset($true);
}
} else {
$r[$key] = $first;
}
}
}
return $r;
}
?>
This should do it, assuming all keys occur in both arrays:
$diff = array();
foreach ($session as $key => $values) {
$diff[$key] = array_diff($values, $post[$key]);
}
Or, because I'm bored and array_map is underused:
$diff = array_combine(
array_keys($session),
array_map(function ($a, $b) { return array_diff($a, $b); }, $session, $post)
);
(Assumed well ordered arrays though.)
You want something more or less like this:
public function array_diff_multidimensional($arr1, $arr2) {
$answer = array();
foreach($arr1 as $k1 => $v1) {
// is the key present in the second array?
if (!array_key_exists($k1, $arr2)) {
$answer[$k1] = $v1;
continue;
}
// PHP makes all arrays into string "Array", so if both items
// are arrays, recursively test them before the string check
if (is_array($v1) && is_array($arr2[$k1])) {
$answer[$k1] = array_diff_multidimensional($v1, $arr2[$k1]);
continue;
}
// do the array_diff string check
if ((string)$arr1[$k1] === (string)$arr2[$k1]) {
continue;
}
// since both values are not arrays, and they don't match,
// simply add the $arr1 value to match the behavior of array_diff
// in the PHP core
$answer[$k1] = $v1;
}
// done!
return $answer;
}

PHP Search multidimensional associative array by key and return key => value

Hi i have a multidimensional associative array:
$array= array(
'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46', )
)
I need to be able to search $array on 'BookX' and then return the contents of 'BookX'.
Ive tried:
function array_searcher($needles, $array)
{
foreach ($needles as $needle) {
foreach ($array as $key )
{
if ($key == $needle)
{
echo $key;
}
}
}
}
with the search
$needles = array('Book1' , 'Book2' );
But this doesnt return anything
I might be misunderstanding, but this just sounds like the accessor. If not, could you clarify?
$array= array(
'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46', )
);
echo $array['Book1'];
EDIT: I did misunderstand your goal. I do have a comment on doing the two foreach loops. While this does work, when you have a very large haystack array, performance suffers. I would recommend using isset() for testing if a needle exists in the haystack array.
I modified the function to return an array of the found results to remove any performance hits from outputing to stdout. I ran the following performance test and while it might not do the same search over and over, it points out the inefficiency of doing two foreach loops when your array(s) are large:
function array_searcher($needles, $array) {
$result = array();
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
if ($key == $needle) {
$result[$key] = $value;
}
}
}
return $result;
}
function array_searcher2($needles, $array) {
$result = array();
foreach ($needles as $needle) {
if (isset($array[$needle])) {
$result[$needle] = $array[$needle];
}
}
return $result;
}
// generate large haystack array
$array = array();
for($i = 1; $i < 10000; $i++){
$array['Book'.$i] = array('http://www.google.com', $i+20);
}
$needles = array('Book1', 'Book2');
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
array_searcher($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 14.2093660831
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
array_searcher2($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 0.00858187675476
If you want to search using the keys, you should access it as a key => value pair.
If you don't it only retrieves the value.
function array_searcher($needles, $array)
{
foreach ($needles as $needle)
{
foreach ($array as $key => $value)
{
if ($key == $needle)
{
echo $key;
}
}
}
}

Categories