I have an array
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
I want to convert this to
$multiarr=array(
[0]=>array(
['id']=>1,
['name']=>'abc'),
[1]=>array(
['id']=>2,
['name']=>'xyz'),
[2]=>array(
['id']=>3,
['name']=>'pqr')
);
id is key and the name is the value of the first array
how can I implement this optimistically
I have done this
$keys=array_keys($arr);
$values=array_values($arr) ;
$multiarr=array();
for($i=0; $i<count($keys); $i++)
{
$multiarr[$i]['id']=$keys[$i];
$multiarr[$i]['name']=$values[$i];
}
Thanks.
Should really be trying this yourself mate, but this should help:
$arr = array(
1=>'xyz',
2=>'abc',
3=>'pqr'
);
$MultiArr = array();
$i = 0;
foreach($arr as $ID=>$Name){
$MultiArr[$i]['id'] = $ID;
$MultiArr[$i]['name'] = $Name;
$i++;
}
print_r($MultiArr);
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 this PHP foreach loop:
foreach($emails_list as $email)
but i want to do something like
foreach($emails_list as $email and $forename_list as $forename)
my code above the foreach loop is:
$sql2="SELECT * from contacts where company_sequence = '".$customersequence."' and contactstatus = '' ";
$rs2=mysql_query($sql2,$conn) or die(mysql_error());
while($result2=mysql_fetch_array($rs2))
{
$emails_list[] = $result2["email"];
}
si i want to be able to include $result["forename"]; within the loop too
will the above work to make 2 loops?
Not sure if understand, but try use for instead:
$emails_list = array("01#gmail.com", "02#gmail.com", "03#gmail.com", "04#gmail.com");
$forename_list = ("01 something", "02 something", "03 something", "04 something");
if($emails_list == $forename_list){
$count = count($emails_list);
for($i=0;$i<$count;$i++){
echo 'Email: '.$emails_list[$i].', Name: '.$forename_list[$i];
}
} else { echo 'Troubles'; }
there is no way to do this in foreach in a one statment
for this use for loop like
for ($i=0;$i<=count($emails_list); $i++) {
echo $emails_list[$i];
echo $forename_list[$i];
}
All the examples listed with a basic for loop will work fine for numeric arrays, however what about associative arrays?
The best way to do this would be something like the following:
$arr_1 = array( 'foo'=>'bar', 'fizz'=>'bang' );
$arr_2 = array( 'hello'=>1, 2=>'world' );
$array_size = count( $arr_1 ); // NOTE: This assumes the arrays are of the same size.
// Reset the internal array pointers
reset( $arr_1 );
reset( $arr_2 );
for ($i = 0; $i < $array_size; $i++ ) {
$first_array_element = current( $arr_1 );
$second_array_element = current( $arr_2 );
// code here
next( $arr_1 );
next( $arr_2 );
}
This will handle both associative and numeric arrays.
I have a arrays like this.
$pahrmacyid=array(
"Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],
"IDQualifier"=>"D3"
)
)
);
$storename=array(
"StoreName"=>$_GET['storename']
);
$pharmacyaddress=array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
);
$communicationnumber=array(
"CommunicationNumbers"=>array(
"Communication"=>array(
"Number"=>$_GET['pCommunicationNumbers'],
"Qualifier"=>"TE"
)
)
);
I want to push this arrays into another array?Is it possible?
I need a result like this:
$result=array(
array("Identification"=>array(
"ID"=>array(
"IDValue"=>$_GET['pharmacyid'],"IDQualifier"=>"D3"
)
)
),
"StoreName"=>$_GET['storename'],array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
),
array(
"Address"=>array(
"AddressLine1"=>$_GET['paddress'],
"City"=>$_GET['pCity'],
"State"=>$_GET['pState'],
"ZipCode"=>$_GET['pZipCode']
)
)
)
It's simple since you have all the array's. Here are a couple of ways to merging all the array's into one multidimensional array.
Example 1:
$example1arr = array(
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 1: <pre>".print_r($example1arr,true)."</pre><br />\n";
Example 2:
$example2arr[] = $pahrmacyid;
$example2arr[] = $storename;
$example2arr[] = $pharmacyaddress;
$example2arr[] = $communicationnumber;
echo "Example 2: <pre>".print_r($example2arr,true)."</pre><br />\n";
Example 3:
$example3arr = Array();
array_push(
$example3arr,
$pahrmacyid,
$storename,
$pharmacyaddress,
$communicationnumber
);
echo "Example 3: <pre>".print_r($example3arr,true)."</pre><br />\n";
$result[] = $pahrmacyid;
And if you have multiple $pahrmacyid-arrays you can add it in a loop.
$result = array();
for($i = 0; $i < count($sourceArray); $i++)
{
$result[] = $sourceArray[$i];
}
$result[] = $pahrmacyid;
You may want to initilize it before with
$result = array();
And I didn't try but maybe the shortcut
$result = array($pahrmacyid);
works...
array_push($result, $pahrmacyid)
or
$result[] = $pahrmacyid
any of these two should do the trick
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];
}
}