Bidimensional array generated dynamically - php

I'm working with dynamic data, so I'm trying to put that data into a bidimensional array.
I need a structure like this:
$array['something1'] = array ( 'hi1' => 'there1' , 'hi2' => 'there2' );
All this data is dynamically generated by a foreach, ex.:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
// set data
$items[$columns[0]] = array ( $columns[1] => $columns[2] );
}
How Can I do the previously described?
Right now the script is stepping over the previous key getting something like this:
$array['something1'] = array ( 'hi2' => 'there2' );
I hope you can help me.
Thanks.

The problem is that you are overwriting the value for the key when it already exists. You should modify to something like:
foreach ( $list as $key => $data )
{
// extract data
$columns = explode ( ';' , $data );
$outer_array_key = $columns[0];
$key = $columns[1];
$value = $columns[2];
// set data
$items[$outer_array_key][$key] = $value;
}

Here is how it can be done:
$list = array ( 0 => 'something;hi1;there1' , 1 => 'something;hi2;there2' );
$newlist =array();
foreach($list as $k=>$v){
$items = explode(';',$v);
$newlist[$items[0]][$items[1]]=$items[2];
}
echo "<pre>";
print_r($newlist);
echo "</pre>";
//output
/*
Array
(
[something] => Array
(
[hi1] => there1
[hi2] => there2
)
)*/
?>

Change your set data with something like this :
if(!array_key_exists($columns[0], $items))
$items[$columns[0]] = array();
$items[$columns[0]][$columns[1]] = $columns[2];

Related

PHP insert array associative - i want to insert a value to existing array in assosciative array

i got question
How to insert value to a existing array, and my expetation of result is like :
Array
(
[id] => 11
[title] => Lorem ipsum
[view] => 3445
)
But what i have did is :
<?php
$newVideo = [
'id'=>'11',
'title'=>'Lorem ipsum'
];
$view = '3445';
$newVideo[] = ['view'=>$view];
print_r($newVideo);
and my result is :
Array
(
[id] => 11
[title] => Lorem ipsum
[0] => Array
(
[view] => 3445
)
)
UPDATE QUESTION: in my case i have complex foreach
in each foreach i want to store the value to variable array like this :
$newVideo = array();
foreach ($videos['items'] as $v){
$id = $v['snippet']['resourceId']['videoId'];
$title = $v['snippet']['title'];
$newVideo[] = [ "id" => $id ,"title" => $title];
the $newVideo is have ['id'] and ['title'] and i want to store ['view'] too, but i have to foreach function first to get the view data from ['id'] so i my code to foreach function to get a view is like :
$funcvid = array();
foreach($newVideo as $id){
$ids = $id['id'];
$vidview = YtJson('apilink', $ids, '');
array_push($funcvid, $vidview);
}
and i got the video statistic so i can grab the view data from that function, so i foreach again to store view data value with this code :
foreach($funcvid as $f){
foreach ($f['items'] as $h){
$view = $h['statistics']['viewCount'];
}
$newVideo['view'] = $view;
}
but for last foreach i can't store the value to $newVideo['view'], it won't lopping, and i got success if array is 2 dimensional, but my expetation is array is 1 dimensional
$newVideo is a 2-dimensional array. You need to index the first dimension to get to the associative inner array.
foreach($funcvid as $i => $f){
foreach ($f['items'] as $h){
$view = $h['statistics']['viewCount'];
}
$newVideo[$i]['view'] = $view;
}
But you don't need 3 different loops, you can do this all in one loop.
<?php
$newVideo = array();
foreach ($videos['items'] as $v){
$id = $v['snippet']['resourceId']['videoId'];
$title = $v['snippet']['title'];
$vidview = YtJson('apilink', $ids, '');
foreach ($vidview['items'] as $h) {
$view = $h['statistics']['viewCount'];
}
$newVideo[] = [ "id" => $id ,"title" => $title, 'view' => $view];
}

Creating multi dimensional array with array of keys

I want to create function which creates multidimensional array from parameter and second parameter should be saved as value here. Expected result is below:
Array
(
[first] => Array
(
[second] => Array
(
[last] => value
)
)
)
what I got so far :
$array = ['first', 'second', 'last'];
function multiArray($array, $newArray = [], $valueToSave)
{
if($array) {
$value = current( $array );
$key = array_search($value, $array);
unset( $array[ $key ] );
$newArray[$value] = [];
return multiArray( $array, $newArray, $valueToSave);
} else {
return $newArray;
}
}
Any tips, what should I change or do next ?
You can try this simplest one.
Try this code snippet here
$array = ['first', 'second', "third", "fourth",'last'];
$value = "someValue";
$result = array();
$count = count($array);
for($x=$count-1;$x>=0;$x--)
{
if($x==$count-1):
$result[$array[$x]]=$value;//setting value for last index
else:
$tempArray = $result;//storing value temporarily
$result = array();//creating empty array
$result[$array[$x]] = $tempArray;//overriting values.
endif;
}
print_r($result);

applying array_unique

I have code to get the address which is separated by space and then fetching area details about that address so each time sql result is stored in array "resultArray" and that result is pushed to another array "returnArray" which is then displayed in the format of json.I want to remove duplicate area_id in returnArray so I used "array_unique" but it's not working .Please give some suggestion.
Sample Code:
<?php
include_once 'main.php';
$dac = new Main();
$add = $_POST['address'];
$noLines = sizeof($add);
$resultArray=array();
$returnArray=array();
$returnArrayMain=array();
while ($noLines>0)
{
$resultArray=array();
$result = $dac->area_detail($add[$noLines-1]);
$count=mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$resultArray[]=array('area_id' => $row['area_id'],'area_name' => $row['area_name'],'area_GISlat'=>$row['area_GISlat'],'area_GISlon'=>$row['area_GISlon']);
}
array_push($returnArray, $resultArray) ;
$noLines = $noLines-1;
}
$returnArrayMain = array_unique($returnArray);
echo json_encode($returnArrayMain);
?>
Here is solution with a testing associative array:
// this is testing array as you are using:
$resultArray = array(
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 11,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3'),
array(
'area_id' => 12,
'area_name' => 'test',
'area_GISlat'=>'test2',
'area_GISlon'=>'test3')
);
// take a temporary arry
$temporaryArr = array();
// initialize key's array
$arrayKey = array();
foreach ( $resultArray as $key => $values ) {
if ( !in_array($values, $temporaryArr) ) {
$temporaryArr[] = $values; // store values in temporary array
$arrayKey[$key] = true; // store all keys in another array
}
}
// now use array_intersect_key function for intersect both array.
$requiredArr = array_intersect_key($resultArray, $arrayKey);
echo "<pre>";
print_r($requiredArr);
Result:
Array
(
[0] => Array
(
[area_id] => 12
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
[1] => Array
(
[area_id] => 11
[area_name] => test
[area_GISlat] => test2
[area_GISlon] => test3
)
)
Removed duplicate arrays.
From PHP Manual:
array_intersect_key — Computes the intersection of arrays using keys for comparison
Side note:
Also add error reporting to the top of your file(s) right after your opening <?php tag
error_reporting(E_ALL);
ini_set('display_errors', 1);
try this
$returnArrayMain = array_map("unserialize", array_unique(array_map("serialize", $resultArray)));
try this..
$returnArrayMain = uniqueAssocArray($returnArray, 'area_id');
echo json_encode($returnArrayMain);
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
$groupBy=$item[$uniqueKey];
if (isset( $uniqueKeys[$groupBy]))
{
//compare $item with $uniqueKeys[$groupBy] and decide if you
//want to use the new item
$replace= ...
}
else
{
$replace=true;
}
if ($replace) $uniqueKeys[$groupBy] = $item;
}
return $uniqueKeys;
}

Build multidimensional array from an array in PHP

I would like to build a multidimensional array from an array. For example I would like
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
to become
$test =
array (
'Tree' => array (
'Trunk' => array (
'Branch' => array (
'Limb' => array (
'Apple' => array (
'Seed' => array ()
)
)
)
)
)
);
or more simply
$result[Tree][Trunk][Branch][Limb][Apple][Seed] = null;
I'm trying to do this with a recursive function but i'm hitting memory limit so I'm clearly doing it wrong.
<?php
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
print_r($test);
print "results of function";
print_r(buildArray($test));
function buildArray (&$array, &$build = null)
{
if (count($array) > 0)
{
//create an array, pass the array to itself removing the first value
$temp = array_values($array);
unset ($temp[0]);
$build[$array[0]] = $temp;
buildArray($build,$temp);
return $build;
}
return $build;
}
Here's an approach with foreach and without recursion, which works:
function buildArray($array)
{
$new = array();
$current = &$new;
foreach($array as $key => $value)
{
$current[$value] = array();
$current = &$current[$value];
}
return $new;
}
[ Demo ]
Now your function... first, using $build[$array[0]] without defining it as an array first produces an E_NOTICE.
Second, your function is going into infinite recursion because you are not actually modifying $array ($temp isn't the same), so count($array) > 0 will be true for all of eternity.
And even if you were modifying $array, you couldn't use $array[0] anymore, because you unset that, and the indices don't just slide up. You would need array_shift for that.
After that, you pass $build and $temp to your function, which results in further because you now you assign $build to $temp, therefore creating another loop in your already-infinitely-recurring loop.
I was trying to fix all of the above in your code, but eventually realized that my code was now pretty much exactly the one from Pevara's answer, just with different variable names, so... that's that.
This function works recursively and does the trick:
function buildArray($from, $to = []) {
if (empty($from)) { return null; }
$to[array_shift($from)] = buildArray($from, $to);
return $to;
}
In your code I would expect you see an error. You are talking to $build in your first iteration as if it where an array, while you have defaulted it to null.
It seems to be easy
$res = array();
$i = count($test);
while ($i)
$res = array($test[--$i] => $res);
var_export($res);
return
array ( 'Tree' => array ( 'Trunk' => array ( 'Branch' => array ( 'Limb' => array ( 'Apple' => array ( 'Seed' => array ( ), ), ), ), ), ), )
Using a pointer, keep re-pointing it deeper. Your two output examples gave array() and null for the deepest value; this gives array() but if you want null, replace $p[$value] = array(); with $p[$value] = $test ? array() : null;
$test = array(
'Tree',
'Trunk',
'Branch',
'Limb',
'Apple',
'Seed'
);
$output = array();
$p = &$output;
while ($test) {
$value = array_shift($test);
$p[$value] = array();
$p = &$p[$value];
}
print_r($output);

Reformatting an array

In short, I need a way to change:
Array
(
[CrmOrder] => Array
(
[crm_schedule_id] => 59
)
)
...into this (using PHP)....
Array
(
[CrmOrder] => Array
(
[0] => Array
(
[crm_schedule_id] => 59
)
)
)
The reason I need to do this is because I want to use the CakePHP saveAll() function with an array that I'm getting from the Wizard Component. Cake's saveAll needs the data to be one level deeper because CrmOrder belongsTo CrmPerson which hasMany CrmOrder.
As this isn't necessarily a Cake specific question, I'm also adding the 'php' tag to this question.
You should be able to leverage the FormHelper to produce the intended output like so:
echo $this->Form->input('CrmOrder.0.crm_schedule_id');
(Note the 0 in dot-notation. See second code block on this page in the manual.)
$input = array( /* your data */ );
$output = $input;
$output['CrmOrder'] = array($output['CrmOrder']);
$newArray = array();
foreach( $oldArray as $key => $value ) {
$newArray[ $key ] = array( $value );
}
Demo:
$data = array(
'CrmOrder' => array(
'crm_schedule_id' => 59,
),
);
$data = array_map(function($v){return array($v);}, $data);
var_dump($data);

Categories