Multi dimension array formatting - php

i want to echo the array value with the key of type , here is my code,
foreach ($sam as $key => $sa) {
foreach ($sa as $s) {
echo $s['type'];
}
}
and this is the content of array $sam
array (size=1)
0 =>
array (size=5)
'type' => string 'days' (length=4)
'bookable' => string 'no' (length=2)
'priority' => int 10
'from' => string '1' (length=1)
'to' => string '1' (length=1)
my serier of foreach code results Warning: Illegal string offset 'type' and i dont know why? can you help me echo type thank you.

You only need one foreach:
foreach ($sam as $s) {
echo $s['type'];
}

Related

Merge inner PHP arrays into one multidimensional array - No duplicates basing on Key value

I have tried a number of PHP functions like array_unique to merge the arrays I have but that does not work since these are not strings.
The starting output would be this on var_dump( $country_cities );
array (size=3)
0 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7886
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Laurence' (length=8)
'city_name_arabic' => string '3684hdfpfwbhisf' (length=15)
1 =>
array (size=1)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
2 =>
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
The Code below merges the different arrays above.
<?php
// Make the cities unique. Remove duplicates form the inner array.
$uniques = [];
foreach($country_cities as $arr ) {
foreach( $arr as $v) {
if( !in_array($v, $uniques, false) ) {
$uniques[$v['country']] = $v;
}
}
}
var_dump($uniques);
Results logged show the code cuts out some of the arrays.
/Users/..... on line php:74:
array (size=2)
'BH' =>
array (size=4)
'post_id' => int 7885
'country' => string 'BH' (length=2)
'city_name_eng' => string 'Bahrain City' (length=12)
'city_name_arabic' => string 'vgdg824762' (length=10)
'KW' =>
array (size=4)
'post_id' => int 7841
'country' => string 'KW' (length=2)
'city_name_eng' => string 'Kuwait City' (length=11)
'city_name_arabic' => string ' مدينة الكويت' (length=24)
Please help figure out my error or suggest a better way to fix it.
If I understood you correctly, this should be the result you wanted to achieve.
Each country code will be included once, while the cities (based on post_id) will only be added once.
<?php
$result = [];
$processedIds = [];
foreach ($country_cities as $ccs) {
foreach ($ccs as $cc => $details) {
// If the country has not yet been added to
// the result we create an outer array.
if (!key_exists($cc, $result)) {
$result[$cc] = [];
}
$postId = $details['post_id'];
if (!in_array($postId, $processedIds)) {
// Add the unique city to country's collection
$result[$cc][] = $details;
// Keep track of the post_id key.
$processedIds[] = $postId;
}
}
}
print_r($result);
<?php
//...
$uniques = [];
foreach($country_cities as $data ) {
foreach( $data as $countryCode => $item) {
if( !array_key_exists($countryCode, $uniques) ) {
$uniques[$countryCode] = []; //Create an empty array
}
$targetArray = &$uniques[$countryCode];
if( !array_key_exists($item['post_id'], $targetArray) ) {
$targetArray[$item['post_id']] = $item; //Create an empty array
}
}
}
Maybe this code will help?

How to avoid errors while parsing through array in PHP?

I am trying to migrate user data from a Drupal database to Wordpress. I'm trying to parse through a data column from Drupal and reorganize it so I can import it where I need to in the Wordpress database. The data column in Drupal is a serialized string:
a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}
I keep getting this error:
Warning: Invalid argument supplied for foreach()
This is my code thus far:
$fixed = preg_replace_callback(
'/s:([0-9]+):\"(.*?)\";/',
function ($matches) { return "s:".strlen($matches[2]).':"'.$matches[2].'";'; },
$data
);
$original_array = unserialize($fixed);
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
};
check with if condition before iteration
if(is_array($original_array) && !empty($original_array)){
foreach ($original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Just cast to an array.
foreach ( (array) $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
You can easily check to see if the variable you're iterating through is an array;
if(isset($original_array) && is_array($original_array)) {
foreach ( $original_array as $key => $value) {
echo $value['profile_membership_type'];
}
}
Edited to include a check to ensure the variable exists.
You have a php serialized string.
I presume the leading f in your question is a typo, as the rest is a valid serialized array:
$array = unserialize('a:12:{s:23:"profile_membership_type";s:4:"Full";s:21:"ms_membership_add_new";s:0:"";s:18:"ms_membership_mpid";s:0:"";s:25:"ms_membership_amount_paid";s:0:"";s:32:"ms_membership_transaction_number";s:0:"";s:30:"ms_membership_current_payments";i:1;s:26:"ms_membership_max_payments";s:0:"";s:24:"ms_membership_start_date";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:27:"ms_membership_should_expire";b:0;s:24:"ms_membership_expiration";a:3:{s:4:"year";s:4:"2014";s:5:"month";s:1:"2";s:3:"day";s:2:"13";}s:20:"ms_membership_status";i:3;s:7:"contact";i:1;}');
var_dump($array);
/*
array (size=12)
'profile_membership_type' => string 'Full' (length=4)
'ms_membership_add_new' => string '' (length=0)
'ms_membership_mpid' => string '' (length=0)
'ms_membership_amount_paid' => string '' (length=0)
'ms_membership_transaction_number' => string '' (length=0)
'ms_membership_current_payments' => int 1
'ms_membership_max_payments' => string '' (length=0)
'ms_membership_start_date' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_should_expire' => boolean false
'ms_membership_expiration' =>
array (size=3)
'year' => string '2014' (length=4)
'month' => string '2' (length=1)
'day' => string '13' (length=2)
'ms_membership_status' => int 3
'contact' => int 1
*/
Note that there is only a single profile_membership_type element, so there is no need to loop:
echo $array['profile_membership_type']; // Full

finding php json array index number

I have a json file with this below format structure.
[
{
"name":"banana",
"type":"fruit",
"rate":10
},
{
"name":"orange",
"type":"fruit",
"rate":20
},
{
"name":"apple",
"type":"fruit",
"rate":30
}
]
I would like to update the rate of the fruit by +1 when i match a search for it.
1 . Read the json file
$json_file = file_get_contents('fruits.txt');
2 . Decoded the json file
$fruit_list=json_decode($json_file,true);
VarDumping the Decoded json file is like this
array (size=3)
0 =>
array (size=3)
'name' => string 'banana' (length=6)
'type' => string 'fruit' (length=5)
'rate' => int 10
1 =>
array (size=3)
'name' => string 'orange' (length=6)
'type' => string 'fruit' (length=5)
'rate' => int 20
2 =>
array (size=3)
'name' => string 'apple' (length=5)
'type' => string 'fruit' (length=5)
'rate' => int 30
Wrote a search function to search the array for fruit name
function search_by_key_and_value($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, search_by_key_and_value($subarray, $key, $value));
}
return $results;
}
$result = search_by_key_and_value($fruit_list,"name",apple);
when the function is supplied with fruit name the whole of json file is searched and the RESULT_MATCH is printed var_dump($result) is like this below
array (size=1)
0 =>
array (size=3)
'name' => string 'apple' (length=5)
'type' => string 'fruit' (length=5)
'rate' => int 30
How can i find the array index number as the result of array index is 0 in the result but its position in the main file point no 3 is indexed at 2 or at-least how can i update the matched retsult rate directly ?

How to force array key's values to be integer instead of string when they are numeric?

How can I force all numeric values to be integer instead of string when some PHP function takes place for exemple with array_replace() ? here is an example:
My $item is an array of default values, which var_dump($item) produces this:
array (size=12)
'id' => string '' (length=0)
'cid' => int 2
'pid' => string '' (length=0)
'rid' => string '' (length=0)
'section' => int 0
'title' => string '' (length=0)
'slug' => string '' (length=0)
'image' => string '' (length=0)
'description' => string '' (length=0)
'ordering' => string '' (length=0)
'created' => string '' (length=0)
'modified' => string '' (length=0)
Then, i call a function to update $item array with new values which comes from db with a function array_replace($item, $item_db);, and when I var_dump($item) again, i get this:
array (size=12)
'id' => string '12' (length=2)
'cid' => string '1' (length=1)
'pid' => string '0' (length=1)
'rid' => string '37' (length=2)
'section' => string '0' (length=1)
'title' => string 'Article2' (length=8)
'slug' => string 'articles123' (length=11)
'image' => string 'e9213e52d235bd892b3337fce3172bed.jpg' (length=36)
'description' => string '' (length=0)
'ordering' => string '3' (length=1)
'created' => string '2014-05-15 14:51:10' (length=19)
'modified' => string '2014-05-15 23:29:40' (length=19)
I want to be all numeric values (id, cid, pid, rid, section, ordering) the integer, except created and modified keys.
How I suppose to do that without manually write each time something like:
$item['section'] = (int) $item['section'];
Is there any solution for this ?
You can use such simple foreach loop:
foreach ($array as $k => $v) {
if ($k != 'created' && $k != 'modified') {
$array[$k] = (int) $v;
}
}
This is of course if you are sure that all values are numeric so they can be converted to int. Otherwise you have to use:
foreach ($item as $k => $v) {
if (is_numeric($v)) {
$item[$k] = (int) $v;
}
}
Create an array containing the values which you'd like to not be renamed. Then loop through your array — on each iteration, check if the current key is in the $defaults array. If it is not, push it into a new array ($results) with the current numeric offset as the key. If not, push it into the new array with the current key:
Something along the lines of:
$defaults = ['created', 'modified']; // Keys to be left untouched
$result = []; // Results array
$i = 0; // Numeric offset
foreach ($array as $key => $value) {
if (!in_array($key, $defaults)) {
$result[++$i] = $value;
} else {
$result[$key] = $value;
}
}
print_r($result);

Why does assigning a new value to an array fail in PHP?

Consider:
array (size=1)
0 =>
array (size=5)
'name' => string '15268459735 Farming and Projects XXXXX' (length=38)
'region' => string '2' (length=1)
'entitynumber' => string '2012/002086/24' (length=14)
'ownership' => string '6' (length=1)
'id' => string '26249' (length=5)
Why does the following still return the same array without the owner element?
foreach ($result as $row)
{
$row['owner'] = 1;
}
Try passing the array by reference:
foreach ($result as &$row) {
$row['owner'] = 1;
}
See also: What's the & for, anyway?

Categories