Flatten multidimensional array not working - php

I have two arrays like the following.
$alerts_array=array(1) {
[0]=> array(11) {
["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
}
}
$singlebtn_array =array(3) {
["button_text0"]=> string(16) "Button Name1only"
["button_text1"]=> string(12) "button name2"
["button_text2"]=> string(16) "button name3_new"
}
I have merged the two arrays into a single multidimensional array which looks like following
$alerts_array = array_merge($alerts_array,$singlebtn_array);
array(4) { [0]=> array(11)
{ ["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
}
[1]=> array(1)
{ ["button_text0"]=> string(16) "Button Name1only" }
[2]=> array(1)
{ ["button_text1"]=> string(12) "button name2" }
[3]=> array(1) { ["button_text2"]=> string(16) "button name3_new" } }
I need both keys and values in the new flattened array
I need it like this:
array(4) { [0]=> array(11)
{ ["CustomAlertsID"]=> int(3)
["CustomAlerts_Name"]=> string(10) "title demo"
["CustomAlerts_PublishDate"]=> string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=> string(10) "2016-07-21"
["button_text0"]=> string(16) "Button Name1only"
["button_text1"]=> string(12) "button name2"
["button_text2"]=> string(16) "button name3_new" }}
I have usedthe following code for combining.
$newArr = array();
foreach ($alerts_array as $key=>$tmp) {
$newArr = array_merge($newArr, array_values($tmp));
}
The $newArr is giving me the result ,but keys are lost

Simply merge the first key [0] of your $alerts_array, like this:
$alerts_array = array_merge($alerts_array[0], $singlebtn_array);
That will output:
array(7) {
["CustomAlertsID"]=>
int(3)
["CustomAlerts_Name"]=>
string(10) "title demo"
["CustomAlerts_PublishDate"]=>
string(10) "2016-07-03"
["CustomAlerts_ExpiryDate"]=>
string(10) "2016-07-21"
["button_text0"]=>
string(16) "Button Name1only"
["button_text1"]=>
string(12) "button name2"
["button_text2"]=>
string(16) "button name3_new"
}
Also see the working demo here.

To get what you want because alerts is an array of arrays:
$alerts_array = array_merge($alerts_array[0],$singlebtn_array);
But with an array of arrays you will probably want a loop. Not sure if each one would be the same thing or if you will have multiples but this will help you.
$alerts_array; //Your array for arrays
singlebtn_array; //Whatever this is
$flattened_alerts_singlebtn = array();
foreach($alerts_array as $alert_array){
//This will be every array in the alerts as your flattened
//array with the singlebtn
$flattened_alerts_singlebt[] = array_merge($alert_array,$singlebtn_array);
}
You can then loop $flattened_alerts_singlebtn to get each falttened array that could exist.

Related

How to loop through the following php array?

I want to loop through the following array.
array(2) {
[0]=> array(6) {
[0]=> string(10) "excel_id "
[1]=> string(12) "excel_name "
[2]=> string(11) "excel_email"
[3]=> string(13) "excel_address"
[4]=> string(12) "excel_giveby"
[5]=> string(16) "excel_accesories"
}
[1]=> array(6) {
[0]=> float(111)
[1]=> string(10) "sh1exname1"
[2]=> string(11) "sh1exemail1"
[3]=> string(12) "sh1exaddress"
[4]=> string(12) "sh1exgivenby"
[5]=> string(16) "sh1exaccesorries"
}
}
can anyone help me?
If you tried anything at all you should have found foreach.
this will loop through all of your array values.
You can simply loop through a multi-dimensional array by using a multi-dimensional foreach like this:
foreach($array as $parentValue)
{
foreach($parentValue as $childValue)
{
// your code
}
}
try this:
foreach ($main_array as $outer_entry){
foreach($outer_entry as $entity){
print_r($entity);
}
}

PHP Multi-Dimensional array search (with array_search)

I am aware of this question, but I have an additional one to search for an array-key. Take a look at this:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Text 1"
["types"]=>
array(3) {
[0]=>
string(7) "Level 1"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor1"
}
}
[1]=>
array(2) {
["name"]=>
string(6) "Text 2"
["types"]=>
array(3) {
[0]=>
string(7) "Level 2"
[1]=>
string(14) "something else"
[2]=>
string(15) "whatisearchfor2"
}
}
}
This snippet...
echo array_search("Text 2", array_column($response, "name"));
...gives me a 1 for the second array-key, in which the term was found.
But how do I receive the global array-key (0 or 1), if I search for whatisearchfor2, which is stored in the multi-array "types"?
echo array_search("whatisearchfor2", array_column($response, "types"));
...doesn't work.
In your case array_column($response, "types") will return an array of arrays. But to get "global array-key (0 or 1), if you search for whatisearchfor2" use the following approach with array_walk:
$key = null; // will contain the needed 'global array-key' if a search was successful
$needle = "whatisearchfor2"; // searched word
// assuming that $arr is your initial array
array_walk($arr, function ($v,$k) use(&$key, $needle){
if (in_array($needle, $v['types'])){
$key = $k;
}
});
var_dump($key); // outputs: int(1)

Converting Json String into PHP array then using php array

Im new to json & php and I'm having some issues with json into php string
My json string looks like this
{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}
So Far i have created my string
$json_raw = '{"status":"OK","cards": [{"id":100001,"name": .....
Decoded the json
$arr = json_decode($json_raw, TRUE);
I var_dump($arr);
then it returns
array(2) { ["status"]=> string(2) "OK" ["cards"]=> array(4) { [0]=> array(8) { ["id"]=> int(100001) ["name"]=> string(6) "batman" ["image"]=> int(11111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T11:37:07Z" } [1]=> array(8) { ["id"]=> int(100002) ["name"]=> string(8) "superman" ["image"]=> int(111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:30:09Z" } [2]=> array(8) { ["id"]=> int(100003) ["name"]=> string(8) "catwoman" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-08-15T12:39:42Z" } [3]=> array(8) { ["id"]=> int(100004) ["name"]=> string(4) "bane" ["image"]=> int(1111111) ["size"]=> int(75) ["region_id"]=> int(1) ["locked"]=> bool(false) ["status"]=> string(6) "active" ["created_at"]=> string(20) "2013-09-08T12:56:04Z" } } }
Now all I want to do is be able to use this data
e.g if name = batman then
I know this is a stupid question but I am struggling :(
Thank in Advance
json_decode() with TRUE as second parameter gives you an associative array. You need to access the correct index to do what you want.
To list the complete associative array with nice formatting, you can do:
echo '<pre>', print_r($arr), '</pre>';
Now, to access the name in your array:
$man = $arr['cards'][0]['name'];
To check if it's Batman (yay!):
if( isset($man) && $man == 'batman' ) {
# code ...
}
For getting the name of all similar names:
$man = $json['cards']['0']['name'];
for ($i=0; $i < count($json['cards']); $i++) {
echo $json['cards'][$i]['name']."\n";
}
See it live!
when you got the array
$arr = json_decode($json_raw, TRUE);
then check if cards key exist
if(array_key_exists('cards', $arr)){
foreach($arr['cards'] as $key=>$val){
echo $key; ///name, id..
echo $val; /// batman,...
if($key == 'name' && $val =='batman'){
//-------do your stuff
}
}
}
Try with:
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
EDIT:
Ok, so this worked for me using code above, try it yourself if you want:
<?php
$json_raw = '{"status":"OK","cards":
[{"id":100001,"name":"batman","image":11111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T11:37:07Z"},
{"id":100002,"name":"superman","image":111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:30:09Z"},
{"id":100003,"name":"catwoman","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-08-15T12:39:42Z"},
{"id":100004,"name":"bane","image":1111111,"size":75,"region_id":1,"locked":false,"status":"active","created_at":"2013-09-08T12:56:04Z"}
]}';
$arr = json_decode($json_raw, TRUE);
$cards = $arr['cards'];
foreach($cards as $card) {
if($card['name'] == 'batman') echo 'Hello batman!';
}
?>

Access elements inside multidimensional array

I have this multidimensional array in PHP:
array(4) {
["took"]=> int(2)
["timed_out"]=> bool(false)
["_shards"]=> array(3) {
["total"]=> int(5)
["successful"]=> int(5)
["failed"]=> int(0)
}
["hits"]=> array(3) {
["total"]=> int(3)
["max_score"]=> float(2.3578677)
["hits"]=> array(1) {
[0]=> array(5) {
["_index"]=> string(13) "telephonebook"
["_type"]=> string(6) "person"
["_id"]=> string(22) "M5vJJZasTGG2L_RbCQZcKA"
["_score"]=> float(2.3578677)
["_source"]=> array(8) {
["Mob"]=> string(19) "XXX"
["Title"]=> string(13) "Analyst"
["Department"]=> string(8) "Analysis"
["Country"]=> string(6) "Sweden"
["Tlf"]=> string(0) ""
["Name"]=> string(16) "XXX"
["Email"]=> string(29) "XX#retro.com"
["thumbnailPhoto"]=> string(0) ""
}
}
}
}
}
The array has several "hits" inside "hits" and I want to loop trough and print out the stuff inside "_source". I have tried a few different approaches but I cant figure out any way to do this. Please help me.
foreach ($array['hits']['hits'][0]['_source'] as $key => $value) {
//do stuff
}
Try this
foreach ($arr['hits']['hits'] as $val)
{
echo $val['_source']['Mob'];
}
like this
I think this may handle it for you. Replace $the_array_you_provided with your "main" array variable (you've not specified it in the post).
$hits = $the_array_you_provided['hits']['hits'];
foreach ($hits as $hit) {
echo $hit['_source']['Title'];
//print everything in the array
//print_r($hit['_source']);
}
Any help feel free to ask.
Try this:
foreach ($array['hits']['hits'] as $hit) {
foreach ($hit['_source'] as $source) {
echo $source, '<br>';
}
}

Bidemensional array to bidemensional array using foreach

Hi I have the following array
array(4) {
[0]=>
array(3) {
["id_acreditado"]=>
string(3) "174"
["cantidad"]=>
string(7) "4008.00"
["acreditado"]=>
string(27) "Olga Olivia Lucio Hernandez"
}
[1]=>
array(3) {
["id_acreditado"]=>
string(3) "175"
["cantidad"]=>
string(7) "4008.00"
["acreditado"]=>
string(23) "Enrique Carranco Vences"
}
[2]=>
array(3) {
["id_acreditado"]=>
string(3) "176"
["cantidad"]=>
string(7) "4008.00"
["acreditado"]=>
string(32) "Juana Patricia Contreras Paredes"
}
[3]=>
array(3) {
["id_acreditado"]=>
string(3) "177"
["cantidad"]=>
string(7) "4008.00"
["acreditado"]=>
string(17) "Noemi Cruz Campos"
}
}
And I want to create a bidimensional array with some values of the above array and different indices. I'm using a foreach loop to achive that.
$j=1;
foreach($acreditados as $acreditado){
$tmp['oneCol'] = $j;
$tmp['twoCol'] = $acreditado['acreditado'];
$tmp['threeCol'] = $acreditado['cantidad'];
$info['fourCol'] =$acreditado['id_acreditado'];
$info[]=$tmp;
$j++;
}
$tmp is an auxiliar one dimension array that lately is added as a row for bidemensional $info array, however I'm not getting the output expected. I want something like the following as output:
array(4) {
[0]=>
array(3) {
["oneCol"]=>
int(1)
["twoCol"]=>
string(27) "Olga Olivia Lucio Hernandez"
["threeCol"]=>
string(7) "4008.00"
["fourCol"]=>
string(3) "174"
}
[1]=>
array(3) {
["oneCol"]=>
int(2)
["twoCol"]=>
string(23) "Enrique Carranco Vences"
["threeCol"]=>
string(7) "4008.00"
["fourCol"]=>
string(3) "175"
}
[2]=>
array(3) {
["oneCol"]=>
int(3)
["twoCol"]=>
string(32) "Juana Patricia Contreras Paredes"
["threeCol"]=>
string(7) "4008.00"
["fourCol"]=>
string(3) "176"
}
[3]=>
array(3) {
["oneCol"]=>
int(4)
["twoCol"]=>
string(17) "Noemi Cruz Campos"
["threeCol"]=>
string(7) "4008.00"
["fourcol"]=>
string(3) "177"
}
}
You have a code error
The line
$info['fourCol'] =$acreditado['id_acreditado'];
Should be
$tmp['fourCol'] =$acreditado['id_acreditado'];
So the code show be: (With the added $tmp array reset)
$j=1;
foreach($acreditados as $acreditado){
$tmp = array();
$tmp['oneCol'] = $j;
$tmp['twoCol'] = $acreditado['acreditado'];
$tmp['threeCol'] = $acreditado['cantidad'];
$tmp['fourCol'] =$acreditado['id_acreditado'];
$info[] = $tmp;
$j++;
}

Categories