I'm tring to add new values to an associative array dynamically and I need your help.
Here is a simple example :
$a = array();
$a["name"]= "n1";
$a["age"]= "age1";
$a["name"]= "n2";
$a["age"]= "age2";
The result is:
Array (2){["name"]=>string(2) "n2" ["age"]=>string(4) "age2" }
I want to add The first age and name and the second age and name to the array. What can I do??
If you want to maintain name <=> age relationship :
$a = array();
$a[] = array("name"=>"n1","age"=>"age1");
$a[] = array("name"=>"n2","age"=>"age2");
UPDATE : usage example below :
foreach ($a as $assoc) {
echo $assoc["name"],' is ',$assoc["age"],'.<br />';
}
$a = array();
array_push($a, array("name"=>"n1","age"=>"age1"));
array_push($a, array("name"=>"n2","age"=>"age2"));
array_push
$a = array();
$a["name"][]= "n1";
$a["age"][]= "age1";
$a["name"][]= "n2";
$a["age"][]= "age2";
You can do by this way
$a = array(
array(
'name' => 'n1',
'age' => 'age1'
),
array(
'name' => 'n2',
'age' => 'age2'
)
);
That's very easy and simple, you can do whatever you want with arrays!! Any doubts? Here you go:
$a = array();
if(is_array($a) && i_can_answer())
{
$keys = array('age', 'name');
$anotherArray = array();
if(is_array($anotherArray ) && i_know_multi_dimensional_arrays())
{
array_push($anotherArray, array("+18", "ILovePHP"));
$result1 = array_combine($keys, $anotherArray);
}
$otherAnotherArray = array();
if(is_array($otherAnotherArray) && i_am_not_tired())
{
array_push($otherAnotherArray , array("+18", "ILovePHP"));
$result2 = array_combine($keys, $otherAnotherArray);
}
$a = array_merge($result1, $result2);
}
print_r($a); //// hoooorrraaaaaaaaaay
Related
I have this general data structure:
$levels = array('country', 'state', 'city', 'location');
I have data that looks like this:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', ... )
);
I want to create hierarchical arrays such as
$hierarchy = array(
'USA' => array(
'New York' => array(
'NYC' => array(
'Central Park' => 123,
),
),
),
'Germany' => array(...),
);
Generally I would just create it like this:
$final = array();
foreach ($locations as $L) {
$final[$L['country']][$L['state']][$L['city']][$L['location']] = $L['count'];
}
However, it turns out that the initial array $levels is dynamic and can change in values and length So I cannot hard-code the levels into that last line, and I do not know how many elements there are. So the $levels array might look like this:
$levels = array('country', 'state');
Or
$levels = array('country', 'state', 'location');
The values will always exist in the data to be processed, but there might be more elements in the processed data than in the levels array. I want the final array to only contain the values that are in the $levels array, no matter what additional values are in the original data.
How can I use the array $levels as a guidance to dynamically create the $final array?
I thought I could just build the string $final[$L['country']][$L['state']][$L['city']][$L['location']] with implode() and then run eval() on it, but is there are a better way?
Here's my implementation. You can try it out here:
$locations = array(
1 => array('country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'count'=>123),
2 => array('country'=>'Germany', 'state'=>'Blah', 'city'=>'NY', 'location'=>'Testing', 'count'=>54),
);
$hierarchy = array();
$levels = array_reverse(
array('country', 'state', 'city', 'location')
);
$lastLevel = 'count';
foreach ( $locations as $L )
{
$array = $L[$lastLevel];
foreach ( $levels as $level )
{
$array = array($L[$level] => $array);
}
$hierarchy = array_merge_recursive($hierarchy, $array);
}
print_r($hierarchy);
Cool question. A simple approach:
$output = []; //will hold what you want
foreach($locations as $loc){
$str_to_eval='$output';
for($i=0;$i<count($levels);$i++) $str_to_eval .= "[\$loc[\$levels[$i]]]";
$str_to_eval .= "=\$loc['count'];";
eval($str_to_eval); //will build the array for this location
}
Live demo
If your dataset always in fixed structure, you might just loop it
$data[] = [country=>usa, state=>ny, city=>...]
to
foreach ($data as $row) {
$result[][$row[country]][$row[state]][$row[city]] = ...
}
In case your data is dynamic and the levels of nested array is also dynamic, then the following is an idea:
/* convert from [a, b, c, d, ...] to [a][b][...] = ... */
function nested_array($rows, $level = 1) {
$data = array();
$keys = array_slice(array_keys($rows[0]), 0, $level);
foreach ($rows as $r) {
$ref = &$data[$r[$keys[0]]];
foreach ($keys as $j => $k) {
if ($j) {
$ref = &$ref[$r[$k]];
}
unset($r[$k]);
}
$ref = count($r) > 1 ? $r : reset($r);
}
return $data;
}
try this:
<?php
$locations = [
['country'=>'USA', 'state'=>'New York', 'city'=>'NYC', 'location'=>'Central Park', 'street'=>'7th Ave', 'count'=>123],
['country'=>'USA', 'state'=>'Maryland', 'city'=>'Baltimore', 'location'=>'Harbor', 'count'=>24],
['country'=>'USA', 'state'=>'Michigan', 'city'=>'Lansing', 'location'=>'Midtown', 'building'=>'H2B', 'count'=>7],
['country'=>'France', 'state'=>'Sud', 'city'=>'Marseille', 'location'=>'Centre Ville', 'count'=>12],
];
$nk = array();
foreach($locations as $l) {
$jsonstr = json_encode($l);
preg_match_all('/"[a-z]+?":/',$jsonstr,$e);
$narr = array();
foreach($e[0] as $k => $v) {
if($k == 0 ) {
$narr[] = '';
} else {
$narr[] = ":{";
}
}
$narr[count($e[0]) -1] = ":" ;
$narr[] = "";
$e[0][] = ",";
$jsonstr = str_replace($e[0],$narr,$jsonstr).str_repeat("}",count($narr)-3);
$nk [] = $ko =json_decode($jsonstr,TRUE);
}
print_r($nk);
Database have three field:
here Name conatin contry state and city name
id,name,parentid
Pass the contry result to array to below function:
$data['contry']=$this->db->get('contry')->result_array();
$return['result']=$this->ordered_menu( $data['contry'],0);
echo "<pre>";
print_r ($return['result']);
echo "</pre>";
Create Function as below:
function ordered_menu($array,$parent_id = 0)
{
$temp_array = array();
foreach($array as $element)
{
if($element['parent_id']==$parent_id)
{
$element['subs'] = $this->ordered_menu($array,$element['id']);
$temp_array[] = $element;
}
}
return $temp_array;
}
I have below two arrays,
$category = array('available', 'notavailable' );
$values = array(1, 2 );
Now i want to get JSON output as below,
[{category: 'available', value:1}{category: 'notavailable', value:2}]
I tried using array_merge array_combine but could not got desired outlut with new Key values category and value,
How can i get that?
Thanks,
You can use array_map, if you have fixed keys:
<?php
$category = array('available', 'notavailable' );
$values = array(1, 2 );
$array = array_map(function($category, $value) {
return ['category' => $category, 'value'=>$value];
}, $category, $values);
echo "<pre>";
var_dump(json_encode($array));
echo "</pre>";
Output:
string(74) "[{"category":"available","value":1},{"category":"notavailable","value":2}]"
I think you must doing like this:
$result = array();
for ($i = 0; $i < count($category); $i++) {
$result[] = array(
'category' => $category[$i],
'value' => $values[$i]
);
}
echo json_encode($result);
I have an array that stores some values. I'm trying to detect the similar values and add them to new array.
example:
$arrayA = array( 1,4,5,6,4,2,1);
$newarray = (4,1);
Any help?
Use the array_intersect() method. For example
$arrayA = array(1,4,5,6,4,2,1);
$arrayB = array(4,1);
$common_values = array_intersect($arrayA, $arrayB);
try this:
$array = array(1,4,5,6,4,2,1);
$duplicates = array_unique(array_diff_assoc($array, array_unique($array)));
$a1 = array( 1,4,5,6,4,2,1);
$a = array();
foreach($a1 as $value){
if(!in_array($value, $a)){
$a[] = $value;
}
}
$arrayA = array(1,4,5,6,4,2,1);
$newarray = array_diff_assoc($arrayA, array_unique($arrayA));
I have two arrays that looks like this:
Array 1, $ids:
$ids = array('8', '56', '33', '23', ... and so on);
Array 2 (multidimensional as well as associative), $positions:
$positions[0] = array('id' => '56',
'latitude' => '45.34234',
'longitude' => '34.23942');
$positions[1] = array('id' => '8',
'latitude' => '49.34834',
'longitude' => '34.93942');
... and so on.
Both arrays contains of id's, but the id's aren't in the same order in the different arrays. What I want is the id's (with their latitudes and longitudes) to be in the same order in $positions as they're in $ids.
How can I do this?
Try this code,
$new_positions = array();
foreach($ids as $k=>$v){
foreach($positions as $k1=>$v1){
if($v == $v1['id']){
array_push($new_positions, $v1);
continue;
}
}
}
$positions = $new_positions;
print_r($positions);
Check here, http://codepad.org/phWxOEC1
Upd: I guess I misunderstood. Sorting $positions by $ids is even easier.
usort($positions, "cmp");
function cmp($a, $b)
{
global $ids;
$a_id = array_search($a['id'], $ids);
$b_id = array_search($b['id'], $ids);
if ($a_id == $b_id) {
return 0;
}
return ($a_id < $b_id) ? -1 : 1;
}
Old version if you need to sort $ids by $positions
First, you need to remember the sorting of id field, since you can't search effectively in associative array like yours.
$sort = array();
$positionsCount = count($positions);
for ($i = 0; $i < $positionsCount; $i++)
{
$sort[ $positions[$i]['id'] ] = $i;
}
Then you can search using usort();.
usort($ids, "cmp");
function cmp($a, $b)
{
global $sort;
if ($sort[$a] == $sort[$b]) {
return 0;
}
return ($sort[$a] < $sort[$b]) ? -1 : 1;
}
This code might need testing, but I hope you got the general idea. If it sorts in reverse, change the -1 : 1 to 1 : -1.
I want to add data to an array dynamically. How can I do that? Example
$arr1 = [
'aaa',
'bbb',
'ccc',
];
// How can I now add another value?
$arr2 = [
'A' => 'aaa',
'B' => 'bbb',
'C' => 'ccc',
];
// How can I now add a D?
There are quite a few ways to work with dynamic arrays in PHP.
Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
$array[] = 'Hi';
pushes on top of the array.
$array['Hi'] = 'FooBar';
sets a specific index.
Let's say you have defined an empty array:
$myArr = array();
If you want to simply add an element, e.g. 'New Element to Array', write
$myArr[] = 'New Element to Array';
if you are calling the data from the database, below code will work fine
$sql = "SELECT $element FROM $table";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)//if it finds any row
{
while($result = mysql_fetch_object($query))
{
//adding data to the array
$myArr[] = $result->$element;
}
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
Like this?:
$array[] = 'newItem';
In additon to directly accessing the array, there is also
array_push — Push one or more elements onto the end of array
$dynamicarray = array();
for($i=0;$i<10;$i++)
{
$dynamicarray[$i]=$i;
}
Adding array elements dynamically to an Array And adding new element
to an Array
$samplearr=array();
$count = 0;
foreach ($rslt as $row) {
$arr['feeds'][$count]['feed_id'] = $row->feed_id;
$arr['feeds'][$count]['feed_title'] = $row->feed_title;
$arr['feeds'][$count]['feed_url'] = $row->feed_url;
$arr['feeds'][$count]['cat_name'] = $this->get_catlist_details($row->feed_id);
foreach ($newelt as $cat) {
array_push($samplearr, $cat);
}
++$count;
}
$arr['categories'] = array_unique($samplearr); //,SORT_STRING
$response = array("status"=>"success","response"=>"Categories exists","result"=>$arr);
just for fun...
$array_a = array('0'=>'foo', '1'=>'bar');
$array_b = array('foo'=>'0', 'bar'=>'1');
$array_c = array_merge($array_a,$array_b);
$i = 0; $j = 0;
foreach ($array_c as $key => $value) {
if (is_numeric($key)) {$array_d[$i] = $value; $i++;}
if (is_numeric($value)) {$array_e[$j] = $key; $j++;}
}
print_r($array_d);
print_r($array_e);
Fastest way I think
$newArray = array();
for($count == 0;$row = mysql_fetch_assoc($getResults);$count++)
{
foreach($row as $key => $value)
{
$newArray[$count]{$key} = $row[$key];
}
}